First create the result type you want to return:
/// <summary> ///return type/// </summary> Public classApiresultmodel {PrivateHttpStatusCode StatusCode; Private Objectdata; Private stringerrormessage; Private BOOLissuccess; /// <summary> ///Status Code/// </summary> PublicHttpStatusCode StatusCode {Get{returnStatusCode;} Set{StatusCode =value;} } /// <summary> ///the returned data/// </summary> Public ObjectData {Get{returndata;} Set{data =value;} } /// <summary> ///error Message/// </summary> Public stringerrormessage {Get{returnerrormessage;} Set{errormessage =value;} } /// <summary> ///is successful/// </summary> Public BOOLissuccess {Get{returnissuccess;} Set{issuccess =value;} } }
Then create the rewrite ActionFilterAttribute under onactionexecuted (after executing the action):
First build a class name arbitrarily as follows: Apiresultattribute inherits the detailed code of System.Web.Http.Filters.ActionFilterAttribute:
The following code should be aware of referencing using System.Net.Http otherwise Readasasync cannot use
Public classApiResultAttribute:System.Web.Http.Filters.ActionFilterAttribute { Public Override voidonactionexecuted (Httpactionexecutedcontext actionexecutedcontext) {Base. OnActionExecuted (ActionExecutedContext); Apiresultmodel result=NewApiresultmodel (); //Gets the status code returned by the APIResult. StatusCode =ActionExecutedContext.ActionContext.Response.StatusCode; //get the data returned by the APIResult. Data = actionexecutedcontext.actioncontext.response.content.readasasync<Object>(). Result; //whether the request was successfulResult. Issuccess =ActionExecutedContext.ActionContext.Response.IsSuccessStatusCode; //result to Custom message formatHttpresponsemessage Httpresponsemessage =Jsonhelper.tojson (Result); //re-encapsulate callback formatActionexecutedcontext.response =Httpresponsemessage; } }
The Jsonhelper.tojson() above is written in the following code: Create Class Jsonhelper
Public Statichttpresponsemessage ToJson (Object obj) {String str; if(obj isString | | Obj isChar)//if the string or character is returned directly{str=obj. ToString (); } Else//Otherwise the sequence is a JSON string{JavaScriptSerializer Serializer=NewJavaScriptSerializer (); STR=Serializer. Serialize (obj); } httpresponsemessage result=Newhttpresponsemessage {Content =NewStringcontent (str, encoding.getencoding ("UTF-8"),"Application/json") }; returnresult; }
After the completion of the registration under the Webapiconfig:
Config. Filters.add (new Apiresultattribute ()); // repack Results
Complete the above steps to use.
WEBAPI (ii)-reseal return results