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

Raj
Raj
Member
34 Points
7 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: 123
Total Answered: 2
Total Marked As Answer: 0
Posted On: 13-Jun-2020 01:08

Share:   fb twitter linkedin
Answers
jk
jk
6 Points
3 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
154 Points
47 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