WebAPI 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.

However, when using the API will always encounter cross-domain requests, especially the various applications of the day, the API cross-domain requests can not be avoided.

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 ways to break this limit, which is well known JSONP, which 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 allows server-side relaxation of cross-domain resource sharing, You can toggle the limit or not restrict cross-domain requests based on the header. 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 Origin value, which is used by the browser to match origin, and 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

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

Method One

1  Public classCroshandler:delegatinghandler2 3 {4 5     Private Const stringOrigin ="Origin";6 7     Private Const stringAccesscontrolrequestmethod ="Access-control-request-method";8 9     Private Const stringAccesscontrolrequestheaders ="access-control-request-headers";Ten  One     Private Const stringAccesscontrolalloworign ="Access-control-allow-origin"; A  -     Private Const stringAccesscontrolallowmethods ="Access-control-allow-methods"; -  the     Private Const stringAccesscontrolallowheaders ="access-control-allow-headers"; -  -     Private Const stringAccesscontrolallowcredentials ="access-control-allow-credentials"; -  +     protected OverrideTaskSendAsync (httprequestmessage request, CancellationToken CancellationToken) -  +     { A  at         BOOLIscrosrequest =request. Headers.contains (Origin); -  -         BOOLIsprefilightrequest = Request. Method = =httpmethod.options; -  -         if(iscrosrequest) -  in         { -  toTaskNULL; +  -             if(isprefilightrequest) the  *             { $ Panax NotoginsengTaskresult = task.factory.startnew -  the                 { +  AHttpresponsemessage response =Newhttpresponsemessage (System.Net.HttpStatusCode.OK); the  + Response. Headers.add (Accesscontrolalloworign, -  $ request. Headers.getvalues (Origin). FirstOrDefault ()); $  -                     stringMETHOD =request. Headers.getvalues (Accesscontrolrequestmethod). FirstOrDefault (); -  the                     if(Method! =NULL) - Wuyi                     { the  - Response. Headers.add (Accesscontrolallowmethods, method); Wu  -                     } About  $                     stringheaders =string. Join (", ", request. Headers.getvalues (Accesscontrolrequestheaders)); -  -                     if(!string. Isnullorwhitespace (headers)) -  A                     { +  the Response. Headers.add (Accesscontrolallowheaders, Headers); -  $                     } the  theResponse. Headers.add (Accesscontrolallowcredentials,"true"); the  the                     returnresponse; -  in }, CancellationToken); the  the             } About  the             Else the  the             { +  -Taskresult =Base. SendAsync (Request, CancellationToken). Continuewith the Bayi                 { the  the                     varResponse =T.result; -  - Response. Headers.add (Accesscontrolalloworign, the  the request. Headers.getvalues (Origin). FirstOrDefault ()); the  theResponse. Headers.add (Accesscontrolallowcredentials,"true"); -  the                     returnresponse; the  the                 });94  the             } the  the             returnTaskresult;98  About         } - 101         return Base. SendAsync (Request, cancellationtoken);102 103     }104  the}

How to use the Global.asax file to add

1 protected voidApplication_Start ()2 3 {4 5 Iocconfig.registerall ();6 7 Arearegistration.registerallareas ();8 9 Webapiconfig.register (globalconfiguration.configuration);Ten  One filterconfig.registerglobalfilters (globalfilters.filters); A  - routeconfig.registerroutes (routetable.routes); -  the bundleconfig.registerbundles (bundletable.bundles); -  -GLOBALCONFIGURATION.CONFIGURATION.MESSAGEHANDLERS.ADD (NewCroshandler ()); -  +}

Method Two

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

<system.webServer> "Access-control-allow-origin"Value="*"/> <add name="access-control-allow-headers"Value="Content-type"/> <add name="Access-control-allow-methods"Value="GET, Post,options"/> </customHeaders> 

original : Jane Xuan Ice . com/jianxuanbing/p/7324929.html

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

WebAPI 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.