How to get http error code in Global.asax in asp.net?

Raj
Raj
648 Points
26 Posts

I'm trying to get http status code of the exception in global.asax but not able to get as:

void Application_Error(object sender, EventArgs e)
{
    var _logger = LogManager.GetCurrentClassLogger();
    var ex = HttpContext.Current.Server.GetLastError();

    var statusCode = HttpContext.Current.Response.StatusCode;
    if (statusCode != 404)
        _logger.Fatal(ex, $"{ex?.Message}");
}

It always giving 200 status code:

Views: 2464
Total Answered: 2
Total Marked As Answer: 2
Posted On: 13-Jun-2020 01:08

Share:   fb twitter linkedin
Answers
jk
jk
34 Points
2 Posts
         

Try to use following code:

void Application_Error(object sender, EventArgs e)
{
    var _logger = LogManager.GetCurrentClassLogger();
    var ex = HttpContext.Current.Server.GetLastError();

    if (ex is HttpException httpEx)
    {
        if (httpEx.GetHttpCode() != 404)
        {
            _logger.Fatal(ex, $"{ex?.Message}");
        }
    }
}
Posted On: 13-Jun-2020 01:35
beginer
beginer
1544 Points
52 Posts
         

Following code will be supported in lower VS, less than VS 2019:

void Application_Error(object sender, EventArgs e)
{
    var _logger = LogManager.GetCurrentClassLogger();
    var ex = HttpContext.Current.Server.GetLastError();

    if (ex is HttpException)
    {
        if ((ex as HttpException).GetHttpCode() != 404)
        {
            _logger.Fatal(ex, ex == null ? "" : ex.Message);
        }
    }
    else
    {
        _logger.Fatal(ex, ex == null ? "" : ex.Message);
    }
}
Posted On: 25-Jul-2020 05:08
 Log In to Chat