The areas of the ASP. NET Web API cross-domain access (CORS)

Source: Internet
Author: User

First, the client requests data with JSONP

If you want to use JSONP to get cross-domain data, WEBAPI itself is not a JavaScript-callback, and it returns JSON like this:

{"yoursignature" "married to marry programmers, money more words less die early "}

However, the JSONP request is expected to receive such JSON:

jQuery123456 ({"yoursignature " " Marry a programmer, the money is too little to die early "})

So we need to expand on WEBAPI and let it support such callback. I have found two ways.

Write yourself a attribute to return the JSON packet callback

 Public classjsoncallbackattribute:actionfilterattribute{Private Const stringCallbackqueryparameter ="Callback";  Public Override voidonactionexecuted (Httpactionexecutedcontext context) {varcallback =string.        Empty; if(Isjsonp ( outcallback)) {            varJsonbuilder =NewStringBuilder (callback); Jsonbuilder.appendformat ("({0})", context. Response.Content.ReadAsStringAsync ().            Result); Context. Response.content=Newstringcontent (jsonbuilder.tostring ()); }        Base.    onactionexecuted (context); }    Private BOOLISJSONP ( out stringcallback) {Callback=Httpcontext.current.request.querystring[callbackqueryparameter]; return!string.    IsNullOrEmpty (callback); }}

Then add this attribute before the method to be called:

[Jsoncallback] [HttpGet] PublicHttpresponsemessage A () {stringStrjson ="{\ "info\": \ "true\"}"; varresult =NewHttpresponsemessage (Httpstatuscode.ok) {Content=NewStringcontent (Strjson, Encoding.UTF8,"Text/plain")            }; returnresult; }

Very concise, but this method has a disadvantage, is added [Jsoncallback] method, can only be applied to JSONP request. If you want the API to be called by clients in a variety of situations, provide support on the server side.

2. Implement with Custom Jsonmediatypeformatter

See the article Artech God: http://www.cnblogs.com/artech/p/cors-4-asp-net-web-api-03.html

The most authentic way to support cors, of course, is to provide support on the service side, according to the official website method, 100% success. Http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api

The main steps are:

1. Install a package to NuGet: http://www.nuget.org/packages/Microsoft.AspNet.WebApi.Cors/

2. Add the code in the Webapiconfig.register method:

Config. Enablecors ();

3. Add attribute to the controller:

" http://myclient.azurewebsites.net " " * " " * ")]

This domain name can be configured, please refer to the official website tutorial given above.

Finally, to tell you a pit, after the service end to provide support, do not be happy too early, if you use Jquery.ajax () to request, or will explode:

$.ajax ({    'yourcorsurl',    ',    '  json',    'GET',     ' Application/json; Charset=utf-8 ' ,    ...})

After countless explosions, and finally found that as long as the datatype and contenttype two parameters removed, it will certainly not explode!!!

The areas of the ASP. NET Web API cross-domain access (CORS)

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.