Application_Error Event handling global exception in ASP. NET MVC Registration Global.asax

Source: Internet
Author: User

in ASP. NET MVC, all unhandled exceptions thrown by the Web site can be captured through the Application_Error event in the application life cycle. As a learning note, this article records the detailed steps for handling and capturing global exceptions using the Global.asax file's Application_Error event.

The article demonstrates that the project was written using the vs2013 compiler: Globalexceptionhandle-by-application_error.zip.

Create a new MVC project in VS2013, where you first turn off custom errors, set the mode of the customerrors node in the Web. config configuration file to off, and note the case:

  <system.web>        <customErrors mode="Off"></customErrors> <compilation debug="true" targetFramework="4.5"/> <httpRuntime targetFramework="4.5"/> </system.web>

To cancel the registration of Handleerrorattribute in the Globalfilter Global filter:

public class FilterConfig{    public static void RegisterGlobalFilters(GlobalFilterCollection filters) { //filters.Add(new HandleErrorAttribute()); }}

Open the Global.asax file and add the Application_Error event code:

ProtectedvoidApplication_Error (Object sender, EventArgs e) {Exception LastError = Server.GetLastError ();if (lasterror! =NULL) {Exception informationString strexceptionmessage =String. Empty;Additional processing for HTTP 404, all other errors as 500 server error HttpException Httperror = LastErrorAs HttpException;if (httperror! =NULL) {Get error codeint httpcode = Httperror.gethttpcode (); Strexceptionmessage = Httperror.message;if (Httpcode = =400 | | httpcode = 404) {Response.statuscode = 404; //jump to the specified static 404 information page, change the URL response.writefile (return;} } strexceptionmessage = Lasterror.message; /*-----------------------------------------------------* This code can be logged as required or processed in other business processes * ---------------------------------------------------*//* * jump to the specified HTTP 500 error Message page * Jump to static page must use Response.WriteFile method */Response.statuscode = 500; Response.WriteFile ( "~/httperror/500.html"); //be sure to call Server.ClearError () otherwise it will trigger error details page (Yellow Pages) Server.ClearError (); Server.Transfer ( "~/httperror/500.aspx");}        

As can be seen from the demo code above, the exception object can be obtained through Server.GetLastError () in the Application_Error event, and related exception information is obtained based on the exception object, including the HTTP error code, Detailed error messages, and so on. In an event, you can write your own business code, such as logging, jumping to a custom error page, and so on.

Where to write code for the Application_Error event

1, Be sure to cancel the Globalfilter global filter Handleerrorattribute registration, but also to check whether there are other global filters in the project to handle the exception, to prevent HTTP 500 types of server errors do not trigger Application_Error events (other types of errors can still be triggered).

You can also turn off the custom error for the Web. config profile:<customerrors mode= "Off" ></customErrors>. Because in general, the custom error page to jump is handled in the Application_Error event, which facilitates setting the HTTP error code.

2, regardless of the final process, in the end of the process or response to the output, be sure to call the Server.ClearError () method to empty the exception, otherwise the exception error is still in an unhandled state, if customErrors mode= "On", then the exception will be handled by the custom error module, unless it is intended to jump to the error page in this way.

If you have closed the custom error but have not called the ClearError method, the detailed error page (commonly known as Yellow Pages) will be raised for ASP.

3, if you want to jump to the static custom error page, use the Response.WriteFile (string filename) method, and finally set the next HTTP status code, such as the following code:

//跳转到指定的静态404信息页面,根据需求自己更改URLResponse.WriteFile("~/HttpError/404.html");Server.ClearError();

4, If you want to use the Server.Transfer (string path) method to jump to the custom error page, there are two points to note:

1th, You must not set the HTTP status code (RESPONSE.STATUSCODE), or it will cause IIS errors, whether it is to jump to a static or dynamic page. For example, the following code:

//Response.StatusCode = 500;//Server.Transfer("~/HttpError/500.html");//Server.Transfer("~/HttpError/500.aspx");

2nd, The Server.Transfer method is incompatible with the routing address and throws an error, and the following code uses routing to throw another exception:

Server.Transfer("~/Home/Index");
Some advantages of using application global errors:

1th, compatibility is good, Web form and MVC can be common, if the old Web Form project is to use Application_Error to handle global exceptions, then in the new MVC project can be easily ported over! The flexibility is also high, and the flexible business code can be written more freely than the custom error of ASP. NET and the HandleError feature of MVC.

In addition, according to the requirements of the HTTP error code, which is also considered an SEO problem, after all, ASP. NET custom error wit is to use 302 rewrite jump, not conducive to SEO. Although the Redirectmode property of the customerrors node can be set to "Responserewrite" (override), the HTTP status code is 200 if the HTTP error code is not set on the page to jump.

Application_Error limitations of Handling site exceptions

The Application_Error event cannot handle an exception that has been handled, such as an exception caught in Try-catch. In addition, because it is an application-level event, it is not possible to handle an operation method or controller-level exception, and I only think of these limitations for the time being, generally, you can use this event to handle custom exceptions as long as there are no special requirements for the project.

Source: http://shiyousan.com/post/635813858052755170

Welcome to reprint This article, this article copyright belongs to the author, reproduced please declare the source or retain this paragraph statement. ^_^ Please respect the results of others ' work and build a better network environment.

Application_Error Event handling global exception in ASP. NET MVC Registration Global.asax

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.