WEBAPI (ii)-reseal return results

Source: Internet
Author: User
Tags tojson

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

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.