Custom error message in ASP.NET MVC when an exception was thrown in the HttpModule

I am using ASP.NET MVC. I catch any unhandled exception on OnExceptionin BaseControllerto correctly display a nice message.

However, I have an Http Module project in the same solution. The module may throw InvalidOperationExceptionif the user makes an incorrect request. I am using IIS7 integrated mode and everything is configured correctly. I am new to IIS and the exception of the Http module.

Googling just found a way to handle exceptions using HttpMethod, which is different from this case.

The question is whether the exception was thrown in the module, will MVC execute or not? If he does, why doesn't he go to OnException? and how to get an exception in MVC, for example, in the Action method?

Edit: Based on @nickvane's answer on the application life cycle, I try to better explain the situation. I think that anyone HttpModuleeven created by me can throw any exception. I want this exception to be handled by my MVC, which is in UrlRoutingModule. I think about:

  • HttpModule Order
  • An unhandled exception stops the module and the next module will never start?
  • How to handle an exception in a MVC ( UrlRoutingModule) web application if it was just added to another HttpModule executed before or after UrlRoutingModule.
  • context.AllErrors context.Error? .

, , - Server.Transfer(), , , , .

: MVC Restful API, MUST JSON. MVC OnException, - { "": " ".}. HttpModule, posibbly . API JSON, . MVC JSON.

+3
1

httpmodule . asp.net:

http://msdn.microsoft.com/en-us/library/bb470252.aspx

asp.net mvc , mvc :

http://ajaxus.net/wp-content/uploads/2010/01/asp_net_mvc_poster.pdf

http://www.asp.net/mvc/tutorials/understanding-the-asp-net-mvc-execution-process-vb

- ASP.NET MVC UrlRoutingModule, HTTP-. . UrlRoutingModule , . ( , RouteBase, , , Route class.) , UrlRoutingModule ASP.NET IIS .

Route UrlRoutingModule IRouteHandler, Route. , MVC MvcRouteHandler. IRouteHandler IHttpHandler IHttpContext . IHttpHandler MVC - MvcHandler . MvcHandler , .

HttpModule , , , . .

httpmodule , , 2 :

  • , . div . .
  • global.asax Application_Error. .

HttpModule , 2. - global.asax, HTTP (400 Bad Request).

HttpModule, Application_Error. , , :

protected void Application_Error()
    {
        var ex = Server.GetLastError(); // get the last exception that was made
        if (ex == null) return; // if there is no exception, just continue
        Response.ClearContent();
        Response.Write("{'error':'" + ex.Message + "'}");
        Response.ContentType = "application/json";
        Response.Flush(); // flush the content to the client
        Response.Close(); // and close the connection so that no other content can be written to the response
        Server.ClearError(); // clear the error so that asp.net does not use the custom error page. If we don't close the response and clear the error, the request will still be handled in the rest of the pipeline.
    }
+4

All Articles