ASP. WebAPI-CORS

Source: Internet
Author: User
Tags script tag string methods

Homologous policy

First, for security reasons, the browser is a mechanism of the same origin policy, which prevents a document or script loaded from one source from getting or setting the properties of another source-loaded document.

A URL must be required for the same origin in the following ways:

    1. Network protocol (HTTP differs from HTTPS)
    2. Domain name
    3. Port (80 differs from 8080)

JSONP

JSONP is a method of cross-domain access. In Web Development We often refer to third-party JS files, this time we will find that the browser does not intercept. JSONP is to make cross-domain access by adding a script tag to a Web page.

general processing in processing JSONP the callback function name and parameter are used as the QueryString To the server , and the server is generated based on the name of the uploaded function. JS passed back to the client.

since the use of the add Script label the way, so JSONP only through GET method to access the server. In addition, because the server to generate JS according to the function name of the upload , so the JSONP method is not the data, but the method call.

in the Demo I wrote a JSONP the server-side build with the client call method.

CORS

For corsAccess-control-allow-origin

Referencing the System.Web.Http.Cors Library

Add System.Web.Http.Cors through NuGet management , I refer to the library named :Microsoft ASP 2.2 cross-origin Support

after referencing the library, first Webapiconfig.register in the first line of the method, add a sentence CONFIG. Enablecors ()( Remember to add to the first line .) I also added at the end of the line, but has been running unsuccessfully, took the long time Kung fu to find is the problem. This is the time to look at the internal implementation of Cors, which should not be the case. )。

public static void Register (httpconfiguration config)  {//WEB API configuration and service config. Enablecors (); Web API Routing config. Maphttpattributeroutes ();   Config. Routes.maphttproute (  name: "Defaultapi",  routetemplate: "Api/{controller}/{action}/{id}",  defaults:new {id = routeparameter.optional});  

System.Web.Http.Cors Library for Cors control is also through characteristics (Attribute) to achieve. the System.Web.Http.Cors Library provides two features with Cors :enablecorsattribute with the Disablecorsattribute , both of these features are based on Controller with the Action the.

[AttributeUsage (AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false)] public sealed class Disablecorsattribute:attribute, Icorspolicyprovider {public disablecorsattribute (); public task<system.web.cors.corspolicy> Getcorspolicyasync (httprequestmessage request, CancellationToken CancellationToken);  

[AttributeUsage (AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false)] public sealed class Enablecorsattribute:attribute, Icorspolicyprovider {public Enablecorsattribute (string origins, String headers, string methods); Enablecorsattribute (string origins, String headers, string methods, string exposedheaders); Public ilist<string> exposedheaders {get,} public ilist<string> Headers {get;} public ilist<string> Methods {get;} public ilist<string> Origins {get,} public long preflightmaxage {get; set; ' public bool ' support scredentials {get; set;}  Public task<system.web.cors.corspolicy> Getcorspolicyasync (httprequestmessage request, CancellationToken CancellationToken);  

enablecorsattribute and disablecorsattribute All implemented interface. But Disablecorsattribute There is no other property associated with the constructor, its usage scenario is roughly when controller has been added enablecorsattribute cors action disable.

Enablecorsattribute corresponds to the response header information , the corresponding relationship is as follows:

cors allow the request domain name, with a comma (,) to the domain of his different domains, such as:/HTTP Localhost:64299,http://www.baidu.com.

for no domain name, you can use an asterisk (*)

TD style= "PADDING-LEFT:7PX; padding-right:7px; Border-top:none; Border-left:none; Border-bottom:solid 0.5pt; Border-right:solid 0.5pt; " > TD style= "PADDING-LEFT:7PX; padding-right:7px; Border-top:none; Border-left:none; Border-bottom:solid 0.5pt; Border-right:solid 0.5pt; " > TD style= "PADDING-LEFT:7PX; padding-right:7px; Border-top:none; Border-left:none; Border-bottom:solid 0.5pt; Border-right:solid 0.5pt; " >  TD style= "PADDING-LEFT:7PX; padding-right:7px; Border-top:none; Border-left:none; Border-bottom:solid 0.5pt; Border-right:solid 0.5pt; " > 

Property

Header information

Note

origins

allow-control-allow-origin

methods

allow-control-allow-method

headers

allow-control-allow-headers

exposedheaders

allow-control-expose-header

preflightmaxage

allow-control-max-age

 

Supportscredentials

Allow-control-allow-credentials

or IE?

During the test I found that I was able to work properly on Firefox. , But here it is. IE No , it's not. , after a search , find to add a word:

JQuery.support.cors = true;

but after adding this sentence, though /api/demo/getfigurebycors It can be adjusted. , but /api/demo/getfigurenocors can also be called. It's depressing, and it's going to be that way. Again after a toss, only to find that this time jQuery is not used XMLHttpRequest, But the use of IE comes with the xdomainrequest component , and the component supports only IE8 and above.

About Demo

in theDemoin the light of the rule of origin, I have defined twoWebProject:api_15with theApi_15.web. api_15in theDemocontrollerthree methods defined separatelyGetfigurebyjsonp,getfigurenocors,getfigurebycorsrespectively forJSONP, non-Cors,Corscalled.

public class Democontroller:apicontroller {public Httpresponsemessage Getfigurebyjsonp (string callback)  { StringBuilder result = new StringBuilder ();   Result. Append ("Callback (");  Result. Append (Jsonconvert.serializeobject (figuremanager.figures));  Result. Append (")"); return new Httpresponsemessage (Httpstatuscode.ok) {Content = new Stringcontent (result. ToString ())};  }  Public ienumerable<figure> getfigurenocors ()  {return figuremanager.figures;  }  [Enablecors (Origins: "*", Headers: "*", Methods: "*")] [Enablecors (Origins: "http://localhost:64299,http:// Www.baidu.com ", headers:" Get,post ", Methods:" * ")] public ienumerable<figure> getfigurebycors ()  {return figuremanager.figures;  }  }

in the Api_15.web only one page is defined in the project, by JQuery of the AJAX to call api_15 of three Action .

Source

Github: Https://github.com/BarlowDu/WebAPI(api_15,api_15.web)

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