Convert exception to HTTP 404 response in Application_Error

First of all, quickly, what exactly do I want to achieve: translate the specific exception into HTTP 404 so that ASP.NET can handle it further .

I handle exceptions in ASP.NET (MVC2) as follows:

    protected void Application_Error(object sender, EventArgs e) {
        var err = Server.GetLastError();
        if (err == null)
            return;
        err = err.GetBaseException();

        var noObject = err as ObjectNotFoundException;
        if (noObject != null)
            HandleObjectNotFound();

        var handled = noObject != null;
        if (!handled)
            Logger.Fatal("Unhandled exception has occured in application.", err);
    }

    private void HandleObjectNotFound() {
        Server.ClearError();
        Response.Clear();
        // new HttpExcepton(404, "Not Found"); // Throw or not to throw?
        Response.StatusCode = 404;
        Response.StatusDescription = "Not Found";
        Response.StatusDescription = "Not Found";
        Response.Write("The whole HTML body explaining whata 404 is??");
    }

The problem is that I cannot configure default customErrorsto work with it. When it is on, it will never be redirected to the page listed in customErrors: <error statusCode="404" redirect="404.html"/>.

I also tried to raise new HttpExcepton(404, "Not Found")from the handler, but then the response code 200, which I do not understand why.

So the questions are:

  • What is the correct way to translate an AnExceptionHTTP response 404?
  • How does a section work customErrorswhen handling exceptions in Application_Error?
  • HttpException (404) (200)?

,
.

+5
1

, HTTP Application_Error, customErrors, Server.ClearError().

Application_Error HttpException.

  • AnException HTTP 404?

. HandleError. HttpException , customErrors.

ObjectNotFoundException HttpException (404)

Application_Error - . API , . Server.TransferRequest() html aspx ( ). asp.net Server.GetLastError Application_Error .

  • customErrors Application_Error?

Server.ClearError(), , customErrors

  • HttpException (404) (200)?

- Application_Error. , .

+2

All Articles