0

How can I handle manually the 404 error in C#?

I want to check some conditions in 404 error and then redirect it to the proper page.

I know the web.config settings, but you can't check conditions in web.config file, can you?

MSajjadi
  • 3,809
  • 3
  • 23
  • 20

2 Answers2

4

Use the HttpStatusCode enumeration, specifically HttpStatusCode.NotFound:

Something like:

WebException we;
HttpWebResponse errorResponse = (HttpWebResponse)we.Response;
if (errorResponse.StatusCode == HttpStatusCode.NotFound)
{
    //
}

Reference: How can I catch a 404?

Similar questions:

Community
  • 1
  • 1
talha2k
  • 24,937
  • 4
  • 62
  • 81
1

I found a solution myself:

var sr = Server.GetLastError() as HttpException;
if (sr.GetHttpCode() == 404)
    ...
MSajjadi
  • 3,809
  • 3
  • 23
  • 20