Based on. Net Framework 4.0 Web API development (5): ASP. NET Web APIs AJAX cross-origin request solution (CORS implementation), apiscors

Source: Internet
Author: User

Based on. Net Framework 4.0 Web API development (5): ASP. NET Web APIs AJAX cross-origin request solution (CORS implementation), apiscors
Overview: 

All users who have used ASP. NET Web APIs are aware that there is no complicated configuration file, and a simple ApiController can work with the required Action. However, when using APIs, cross-origin requests always occur,
Cross-origin API requests cannot be avoided even when various apps are released.

By default, to prevent cross-site forgery (CSRF) attacks (or javascript Same-Origin Policy )), when a webpage obtains data from another domain, it will receive restrictions. There are some ways to break through this restriction, that is, the well-known JSONP,
Of course, this is only one of the many solutions. Because JSONP only supports GET requests, today's complex services cannot meet the requirements. CORS (Cross Origin Resource Sharing https://www.w3.org/wiki/CORS) is a new header specification,
This allows the server to relax the cross-origin restrictions. You can switch between the limits based on the header or not restrict cross-origin requests. It supports all http request methods.

Problem:

For XMLHttpRequest cross-origin POST or GET requests, the request method is automatically changed to OPTIONS.
Due to the CORS (cross origin resource share) specification, the browser will first send an options sniffing and the header carries the origin to determine whether the cross-origin request permission exists, the server responds to the value of access control allow origin,
The browser matches the origin. If the origin matches, the post request is formally sent. Even if the server permits cross-origin access, the request will die if the options request is not supported.

Cause:

For the sake of security, the browser will use the transparent Server Authentication Mechanism of the Preflighted Request to support developers to use methods other than custom headers, GET or POST, and different types of topic content, that is, an options request will be sent first,
Ask the server if the request is correct (allowed) to ensure that the request is sent securely.

OPTIONS is generally used as follows:
1. Non-GET or POST requests
2. the content-type of the POST request is not the common three: application/x-www-form-urlencoded (form submitted using the http post method), multipart/form-data (same as above, but mainly used when the form is submitted with file upload), text/plain (plain text)
3. the payload of the POST request is text/html.
4. Set custom Headers

The OPTIONS Request header contains the following Headers: Origin, Access-Control-Request-Method, and Access-Control-Request-Headers. After this Request is sent, the server can set the following header to communicate with the browser to determine whether the request is allowed.
Access-Control-Allow-Origin, Access-Control-Allow-Method, Access-Control-Allow-Headers

Solution:

Method 1:

This method is powerful and can solve complicated cross-origin requests of ASP. NET Web APIs, carrying complex header information, body content and authorization authentication information.

1 public class CrosHandler: DelegatingHandler 2 {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 10 protected override Task <HttpResponseMessage> SendAsync (HttpRequestMessage request, system. threading. cancellationToken cancellationToken) 11 {12 bool isCrosRequest = request. headers. contains (_ origin); 13 bool isPreflightRequest = request. method = HttpMethod. options; 14 if (isCrosR Equest) 15 {16 Task <HttpResponseMessage> taskResult = null; 17 if (isPreflightRequest) 18 {19 taskResult = Task. factory. startNew <HttpResponseMessage> () => 20 {21 HttpResponseMessage response = new HttpResponseMessage (System. net. httpStatusCode. OK); 22 response. headers. add (_ accessControlAllowOrigin, request. headers. getValues (_ origin ). firstOrDefault (); 23 string method = request. headers. getValues (_ access ControlRequestMethod). FirstOrDefault (); 24 if (method! = Null) 25 {26 response. headers. add (_ accessControlAllowMethods, method); 27} 28 string headers = string. join (",", request. headers. getValues (_ accessControlRequestHeaders); 29 if (! String. isNullOrEmpty (headers) 30 {31 response. headers. add (_ accessControlAllowHeaders, headers); 32} 33 return response; 34}, cancellationToken); 35} 36 else37 {38 taskResult = base. sendAsync (request, cancellationToken) 39. continueWith <HttpResponseMessage> (t => 40 {41 var response = t. result; 42 response. headers. add (_ accessControlAllowOrigin, request. headers. getValues (_ origin ). firstOrDefault (); 43 return response; 44}); 45} 46 return taskResult; 47 // return base. sendAsync (request, cancellationToken); 48} 49 else50 {51 return base. sendAsync (request, cancellationToken); 52} 53} 54}View Code 1 protected void Application_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); 10 BundleConfig. registerBundles (BundleTable. bundles); 11 12 GlobalConfiguration. configuration. messageHandlers. add (new CrosHandler (); 13}View Code

Method 2:

Add the following configuration in the configuration file. This method is simple to handle simple cross-origin requests.

1 <system.webServer>2     References:

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

 

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.