In MVC, we know that there is a built-in filter method, that is, the AOP horizontal aspect programming.
First, customize the customefilterattribute class, inherit the filterattribute method, and inherit the iexceptionfilter interface.
(You can also inherit iactionfilter, iauthorizationfilter, iresultfilter, and other interfaces), and then implement the onexception method.
First lookCode:
Public class customefilterattribute: filterattribute, iexceptionfilter {
Public void onexception (exceptioncontext filtercontext)
{
// Errlog path
String Path = httpcontext. Current. server. mappath ("/logs/errlogs.txt ");
// Error time
String errtime = datetime. Now. tostring ();
// Error Type
String errtype = filtercontext. Exception. GetType (). tostring ();
// Error message
String errmessage = filtercontext. Exception. message;
// Method for exception
String targetsite = filtercontext. Exception. targetsite. tostring ();
// The object that causes the exception
String source = filtercontext. Exception. Source. tostring ();
// Exception controller name
String controller = filtercontext. routedata. Values ["controller"]. tostring ();
// Abnormal action name
String action = filtercontext. routedata. Values ["action"]. tostring ();
String errstr = string. format ("Time: {0}, Error Type: {0}, error message: {2}, exception method: {3}, exception object: {4 }, controller name: {5}, action name: {6} ", errtime, errtype, errmessage, targetsite, source, controller, action); writelog (path, true, errstr );
}
Private void writelog (string path, bool append, string errstr)
{
Streamwriter writer = new streamwriter (path, append );
Writer. writeline (errstr );
Writer. Flush ();
Writer. Dispose ();
}
}
Now we have implemented the err writing method. Next, let's take a look at how to capture err.
We want to customize a basecontroller
[Customefilter]
Public class basecontroller: Controller
{
Public basecontroller ()
{
}
}
Then, let all the controllers you write inherit the basecontroller to catch exceptions.