ASP. NET Web api2.0 Ajax Cross Domain solution

Source: Internet
Author: User

The advantages and disadvantages of the Web API is not to say, directly say how cross-domain, I searched, mainly there are two kinds.

One, the ASP. NET Web API supports JSONP in two types of

1, using Jsonmediatypeformatter, specific reference here: http://www.cnblogs.com/artech/p/cors-4-asp-net-web-api-03.html

On the code:

New Jsonpmediatypeformatter class:

     Public classJsonpmediatypeformatter:jsonmediatypeformatter {Private stringCallbackqueryparameter;  PublicJsonpmediatypeformatter () {supportedmediatypes.add (defaultmediatype); Supportedmediatypes.add (NewMediatypeheadervalue ("Text/javascript")); Mediatypemappings.add (NewUripathextensionmapping ("Jsonp", Defaultmediatype)); }         Public stringCallbackqueryparameter {Get{returnCallbackqueryparameter??"Callback"; } Set{Callbackqueryparameter =value;} }        /// <summary>        ///fills the JSON string after the object is serialized into the JavaScript callback function/// </summary>        /// <param name= "type" ></param>        /// <param name= "value" ></param>        /// <param name= "stream" ></param>        /// <param name= "content" ></param>        /// <param name= "TransportContext" ></param>        /// <returns></returns>         Public OverrideTask writetostreamasync (Type type,Objectvalue, Stream stream, httpcontent content, TransportContext transportcontext) {            stringcallback; if(Isjsonprequest ( outcallback)) {                returnTask.Factory.StartNew (() =                {                    varwriter =NewStreamWriter (stream); Writer. Write (Callback+"("); Writer.                    Flush (); Base. Writetostreamasync (type, value, stream, content, TransportContext).                    Wait (); Writer. Write (")"); Writer.                Flush ();            }); }            Else            {                return Base.            Writetostreamasync (type, value, stream, content, transportcontext); }        }        /// <summary>        ///to determine whether a cross-domain request/// </summary>        /// <param name= "callback" ></param>        /// <returns></returns>        Private BOOLIsjsonprequest ( out stringcallback) {Callback=NULL; if(HttpContext.Current.Request.HttpMethod! ="GET")                return false; Callback=Httpcontext.current.request.querystring[callbackqueryparameter]; return!string.        IsNullOrEmpty (callback); }    }

    • Register Jsonpmediatypeformatter in Global.asax
    • GlobalConfiguration.Configuration.Formatters.Insert (0new jsonpmediatypeformatter ());

2, using ActionFilterAttribute, specific reference here: http://stackoverflow.com/questions/9421312/jsonp-with-asp-net-web-api/18206518#18206518

Code:

New Jsoncallbackattribute Class

     Public classJsoncallbackattribute:actionfilterattribute {Private Const stringCallbackqueryparameter ="Callback";  Public Override voidonactionexecuted (Httpactionexecutedcontext actionexecutedcontext) {varcallback =string.            Empty; if(ISJOSNP ( outcallback)) {                varJsonbuilder =NewStringBuilder (callback); Jsonbuilder.appendformat ("({0})", ActionExecutedContext.Response.Content.ReadAsStringAsync ().                Result); ActionExecutedContext.Response.Content=NewStringcontent ("C (\ "A\")"); }            Base.        OnActionExecuted (ActionExecutedContext); }        Private BOOLISJOSNP ( out stringcallback) {Callback=System.web.httpcontext.current.request.querystring[callbackqueryparameter]; return!string.        IsNullOrEmpty (callback); }    }

Register Jsoncallbackattribute in Global.asax

GLOBALCONFIGURATION.CONFIGURATION.FILTERS.ADD (new Jsoncallbackattribute ());

Two, use the Microsoft ASP. NET Web API 2 Cross-origin suppor

Install Microsoft ASP 2 Cross-origin support using Nuge, which is very detailed here

The support for Cors is then opened in the Global.asax, and Enablecors does not have an impact.

Test Example:

<! DOCTYPE html>"http://www.w3.org/1999/xhtml">"Server"> <meta http-equiv="Content-type"Content="text/html; Charset=utf-8"/> <script src="Http://cdn.bootcss.com/jquery/2.1.3/jquery.min.js"></script> <title> Test WebApi cross-domain </title>"Form1"runat="Server"> <input type="Button"Id="Btnget"Value="Get Click to query data across domains"/> <div id="Binddata"> </div> <input type="Button"Id="Btnpost"Value="Post Click Query data across Domains"/> </form> <script>        $('#btnGet'). Bind ('Click', Function (e) {$.ajax ({type:"GET", URL:"Http://localhost:20128/api/UserInfo", Success:function (data) {varHTML =""; $.each (data, function (index, val) {html+="<ul><li>groupname:"+ val. Id +" -- "+ val. Name +"</li></ul>";                    }); $("#bindData"). append (HTML);        }            });        }); $('#btnPost'). Bind ('Click', Function (e) {varuser = {Id:'1', Name:'233' }; $.ajax ({type:"POST", ContentType:'Application/json; Charset=utf-8', data:JSON.stringify (user), URL:"Http://localhost:20128/api/UserInfo", Success:function (data) {//var html = ""; //$.each (data, function (index, VAL) {//html + = "<ul><li>groupname:" + val. Id + "--" + val.                    Name + "</li></ul>"; //}); //$ ("#bindData"). Append (HTML);                }            });    }); </script></body>

Ajax requests at the time of post data, be sure to add such an entry:

' Application/json; Charset=utf-8 ' , data:JSON.stringify (user),

In this way, just put a solution on the network to tidy up a bit, put in everything.

ASP. NET Web api2.0 Ajax Cross Domain solution

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.