Based on the. Net Framework 4.0 Web API Development (5): ASP. AJAX cross-Domain request resolution (Cors implementation)

Source: Internet
Author: User

Overview:  

The ASP. NET Web API is easy to use and knows that without a complex configuration file, a simple Apicontroller plus action is required to work. But there are always cross-domain requests when using the API,
Especially with all kinds of apps, the cross-domain request of API is unavoidable today.

By default, in order to prevent CSRF cross-site forgery attacks (or JavaScript's same-origin policy), a Web page receives restrictions when it obtains data from another domain. There are some ways to break this limit, and that is the familiar JSONP,
Of course, this is only one of many solutions, because JSONP only supports GET requests, today's complex business is not enough to meet the requirements. and the CORS (cross Origin Resource sharing Https://www.w3.org/wiki/CORS) is a new header specification that is shared across domain resources.
You can let the server side relax the cross-domain limit, and you can switch restrictions based on the header or not limit cross-domain requests. It is important that it supports all HTTP request methods.

Problem:

XMLHttpRequest a cross-domain post or GET request, the request will automatically become an options issue.
Due to the existence of the cors (cross Origin resource share) specification, the browser will first send an options sniff, and the header takes origin to determine if there is a request permission across domains, and the server responds to access control allow The value of origin,
For the browser to match origin, if the match formally sends a POST request, even if the server allows the program to cross-domain access, the request will also die if the options request is not supported.

Reason:

Browser for security purposes, the transparent server validation mechanism that preflighted request enables developers to use custom headers, get or post methods, and different types of topic content, which means that an options request is sent first.
Ask the server if it will (allow) the request correctly, and ensure that the request is sent securely.

Where OPTIONS are present, it is generally:
1, non-GET, POST request
2. The content-type of the POST request is not a regular three: application/x-www-form-urlencoded (Form submitted using the Post method of HTTP), Multipart/form-data (Ibid., But mainly used when the form submits with the file upload, Text/plain (plain text)
3, the payload of the POST request is text/html
4. Set the custom header

The options request header will contain the following headers: Origin, Access-control-request-method, Access-control-request-headers, after sending this request, The server can set the following header to communicate with the browser to determine whether to allow this request.
Access-control-allow-origin, Access-control-allow-method, access-control-allow-headers

Workaround:

Method One:

This method is powerful to address complex cross-domain requests for ASP. Complex header information, body content, and authorization verification information

1      Public classCroshandler:delegatinghandler2     {3         Private Const string_origin ="Origin";4         Private Const string_accesscontrolrequestmethod ="Access-control-request-method";5         Private Const string_accesscontrolrequestheaders ="access-control-request-headers";6         Private Const string_accesscontrolalloworigin ="Access-control-allow-origin";7         Private Const string_accesscontrolallowmethods ="Access-control-allow-methods";8         Private Const string_accesscontrolallowheaders ="access-control-allow-headers";9 Ten         protected OverrideTaskSendAsync (httprequestmessage request, System.Threading.CancellationToken CancellationToken) One         { A             BOOLIscrosrequest =request. Headers.contains (_origin); -             BOOLIspreflightrequest = Request. Method = =httpmethod.options; -             if(iscrosrequest) the             { -TaskNULL; -                 if(ispreflightrequest) -                 { +Taskresult = task.factory.startnew -                     { +Httpresponsemessage response =Newhttpresponsemessage (System.Net.HttpStatusCode.OK); A Response. Headers.add (_accesscontrolalloworigin, request.) Headers.getvalues (_origin). FirstOrDefault ()); at                         stringMETHOD =request. Headers.getvalues (_accesscontrolrequestmethod). FirstOrDefault (); -                         if(Method! =NULL) -                         { - Response. Headers.add (_accesscontrolallowmethods, method); -                         } -                         stringheaders =string. Join (", ", request. Headers.getvalues (_accesscontrolrequestheaders)); in                         if(!string. IsNullOrEmpty (headers)) -                         { to Response. Headers.add (_accesscontrolallowheaders, Headers); +                         } -                         returnresponse; the }, CancellationToken); *                 } $                 ElsePanax Notoginseng                 { -Taskresult =Base. SendAsync (Request, CancellationToken) the. Continuewith +                         { A                             varResponse =T.result; the Response. Headers.add (_accesscontrolalloworigin, request.) Headers.getvalues (_origin). FirstOrDefault ()); +                             returnresponse; -                         }); $                 } $                 returnTaskresult; -                 //return base. SendAsync (Request, cancellationtoken); -             } the             Else -             {Wuyi                 return Base. SendAsync (Request, cancellationtoken); the             } -         } Wu}
View Code
1      protected voidApplication_Start ()2         {3 Iocconfig.registerall ();4 5 Arearegistration.registerallareas ();6 7 Webapiconfig.register (globalconfiguration.configuration);8 filterconfig.registerglobalfilters (globalfilters.filters);9 routeconfig.registerroutes (routetable.routes);Ten bundleconfig.registerbundles (bundletable.bundles); One  AGLOBALCONFIGURATION.CONFIGURATION.MESSAGEHANDLERS.ADD (NewCroshandler ()); -}
View Code

Method Two:

The configuration file adds the following configuration, which is simple and should be used for simple cross-domain requests

1<system.webServer>23<customHeaders>4<add name="Access-control-allow-origin"Value="*"/>5<add name="access-control-allow-headers"Value="Content-type"/>6<add name="Access-control-allow-methods"Value="GET, Post,options"/>7</customHeaders>89<system.webServer>
Reference documents:

Https://code.msdn.microsoft.com/windowsdesktop/Implementing-CORS-support-a677ab5d#content

Based on the. Net Framework 4.0 Web API Development (5): ASP. AJAX cross-Domain request resolution (Cors implementation)

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.