In fact, the existing framework of AOP on the net should be quite a lot, such as static injection of POSTSHARP (the new version seems to have been commercialized, the old version does not support. net4.0+), or by reflection (performance degrades).
This article is based on one of the methods of MVC Interceptor Actionfilter (reference online already has many similar examples).
First, create a new log control class named Apilogattribute, inherited from ActionFilterAttribute
/// <summary> ///logging access logs and site security checks/// </summary> Public classApilogattribute:actionfilterattribute {#regionPropertyPrivate stringLogType; PublicApilogattribute (stringtype) {LogType=type; } #endregion Public Override voidonactionexecuting (Httpactioncontext actioncontext) {if(string. IsNullOrEmpty (LogType))return; Accesssummaryhelper.addonevisit (LogType);//code that implements its own interface traffic statistics//Here you can agree to add some interface checks to avoid invalid requests. Return //The check does not pass, then returns directly, does not enter the method bodyActioncontext.response = ActionContext.Request.CreateResponse (Httpstatuscode.ok,Newapiresult{code=1, msg="invalid request. "}); } }
Next, build an interface method cache class, named Apicacheattribute, inherited from ActionFilterAttribute
Public classApicacheattribute:actionfilterattribute//, System.Web.Mvc.ActionFilterAttribute {
Set the cache time by default of 1 minutesPrivatecachetimeoption CacheTime; PublicApicacheattribute (Cachetimeoption cachetime =cachetimeoption.oneminute) {cacheTime=Cachetime; } Public Override voidonactionexecuting (Httpactioncontext actioncontext) {Base. OnActionExecuting (Actioncontext); stringCacheKey =HttpContext.Current.Request.RawUrl; Apiresult ret= cachehelper.get<apiresult>(CacheKey); //when a request is terminated before the action executes, the Fill method response should be used, and the action method body will not be returned. if(Ret! =NULL) {Actioncontext.response=ActionContext.Request.CreateResponse (Httpstatuscode.ok, ret); } } Public Override voidonactionexecuted (Httpactionexecutedcontext actionexecutedcontext) {stringCacheKey =HttpContext.Current.Request.RawUrl; varobj =( (objectcontent) (actionExecutedContext.Response.Content)). Value; if(obj! =NULL) {apiresult ret= obj asApiresult; if(Ret! =NULL) {Cachehelper.set (CacheKey, ret, cacheTime); } } } }
Note that the above Apiresult returns the class for the custom interface.
Public class apiresult{ publicintgetset;} Public getset
Publicobjectgetset
}
Finally, the following is called on the specific class interface:
Public class Xxcontroller:apicontroller { [httpget] [Apicache] [Apilog ("1.1")] public apiresult getxx () { // business code slightly }}