ASP. NET Web API 2 support for CORS

Source: Internet
Author: User
Tags domain list

Cors Concept

Cross-domain resource sharing (CORS) is a World Wide Web Consortium specification (often considered a part of HTML5) that allows JavaScript to overcome the same domain policy security restrictions imposed by the browser. The so-called same-domain policy is that JavaScript can only make AJAX callbacks to the same domain that contains the Web page (where "domain" is a combination of host name, protocol, and port number). For example, JavaScript on a webpage in http://foo.com cannot be http://bar.com (or http://www.foo.com, https://foo.com, or http://foo.com:999 And so on) for AJAX calls.

CORS relaxes this restriction by letting the server indicate which domains are allowed to invoke them. Cors is enforced by the browser and must be implemented on the server, and the latest version of ASP. NET Web API 2 fully supports CORS. with Web API 2, you can configure policies to allow JavaScript clients from different domains to access your APIs.

CORS Basic Information

Because the Web API is fully implemented in this specification, it is helpful to learn more about Cors itself in order to use the new Cors feature in the Web API. These details may now seem theoretical, but will be useful for understanding the settings available in the Web API in the future: When you debug CORS, these things can help you solve problems more quickly.

The general mechanism of CORS is that when JavaScript attempts to cross-domain AJAX calls, the browser "asks" whether the server allows such a call by sending a header (such as "Origin") in an HTTP request. The server indicates the allowed operation by returning an HTTP header (such as "Access-control-allow-origin") in the response. This permission check will be done for each different URL that the client invokes, which means that different URLs can have different permissions.

In addition to domains, CORS allows the server to indicate which HTTP methods are allowed, which HTTP request headers the client can send, what HTTP response headers the client can read, and whether the browser is allowed to send or receive credentials automatically (Cookie or authorization header). the other request and response headers indicate which of these features are allowed to be used. Figure 1 summarizes these headers (note that some features do not have headers sent in the response, only responses).

Figure 1 CORS HTTP Header

Permissions/Features Request headers Response headers
Domain Domain Access-control-allow-origin
HTTP method Access-control-request-method Access-control-allow-method
Request headers Access-control-request-headers Access-control-allow-headers
Response headers Access-control-expose-headers
Credentials Access-control-allow-credentials
Cache Pre-check response Access-control-max-age

Browsers can request these permissions from the server in two different ways: simple cors requests and pre-check cors requests.

Web API 2 for CORS support

Cors support in the Web API is a complete framework that allows applications to define permissions for Cors requests. the framework is expanded around a policy scenario that allows you to specify the CORS functionality allowed for any given request to enter the application.

First, in order to get the cors framework, you must reference the Cors library from the Web API application (by default, none of the Web API templates in Visual Studio 2013 reference These libraries). the Web API CORS Framework is provided through NuGet as a Microsoft.AspNet.WebApi.Cors package. Early NuGet input

Install-package Microsoft.AspNet.WebApi.Cors

Note that the Web API 2 pair, the NET Framework requires more than 4.5, after you install the package above, you will find that there are two more important packages in the reference, as shown in

Next, in order to express this policy, the Web API provides a custom attribute class named Enablecorsattribute. This class contains properties for the allowed domains, HTTP methods, request headers, response headers, and whether credentials are allowed (they model all the details of the CORS specification described earlier).

Finally, in order for the Web API cors framework to process the Cors request and issue the appropriate cors response header, the class must check each request that enters the application. the Web API provides extension points for this interception operation through message handlers. the Web API CORS Framework implements a message handler named Corsmessagehandler accordingly. for Cors requests, the handler queries the policy expressed in the properties of the called method and issues the appropriate cors response header.

Enablecorsattribute. The Enablecorsattribute class is the way applications express their CORS policies. the Enablecorsattribute class has an overloaded constructor that can accept three or four parameters. These parameters (in turn) are:

    1. List of allowed domains
    2. Allow Request Header List
    3. Allow HTTP method list
    4. Allow response header list (optional)

There is also a property that allows credentials (supportscredentials) and another attribute (Preflightmaxage) that specifies the value of the preflight cache duration.

As an example of the default API program established by VS2013, after the WEBAPI reference program is built, two control zones, one HomeController and one valuecontroller, are automatically generated under the Controller folder. We mainly look at the Valuecontroll, this controller inherits the Apicontroller, visible is a webapi, we add a global enablecors property on Valuecontroller, to try it to support cross-domain, as shown in

Note that each constructor argument is a string. you can represent multiple values by specifying a comma-delimited list. if you want to allow all domains, request headers, or HTTP methods, you can use "*" as a value (you must still explicitly specify for the response header).

In addition to applying the Enablecors property at the method level, you can apply the property at the class level or apply it globally to the application. The level at which the attribute is applied configures CORS in the Web API code for all requests at that level and below. For example, if the policy is applied at the method level, the policy applies only to requests for that operation, and if the policy is applied at the class level, the policy applies to all requests to that controller. Finally, if the policy is applied globally, the policy applies to all requests.

If a policy exists in more than one location, the closest property is used and the other properties are ignored (precedence is method, class, global). If you have applied a policy at a higher level, but then want to exclude a request at a lower level, you can use another attribute class named Disablecorsattribute. This property is essentially a policy that does not allow permissions.

If there are other methods on the controller that you do not want to allow CORS, there are two choices. First, you can explicitly specify it in the HTTP method list. Alternatively, you can leave the wildcard character, but use the Disablecors property to exclude the Delete method.

Corsmessagehandler. Corsmessagehandler must be enabled for the Cors framework to perform its work of intercepting requests to evaluate cors policies and issue cors response headers. message handlers are typically enabled in the application's Web API configuration class by calling the Enablecors extension method:

   Public Static classWebapiconfig { Public Static voidRegister (httpconfiguration config) {//Web API Configuration and Services//Web API RoutingCONFIG.            Maphttpattributeroutes (); Config. Routes.maphttproute (Name:"Defaultapi", Routetemplate:"Api/{controller}/{id}", defaults:New{id =routeparameter.optional}); Enable cross-domain config.        Enablecors (); }    }

Entering http://localhost:19881/api/values in the browser appears as follows, indicating that the WEAPI is already available.

So next, we're going to test the cross-domain, create a new MVC application, and set the port number to 19894.

Where the code for the Home/index page is shown below

@{    Layout = null;} <! DOCTYPE html>

  

The code is simple, put a button, and use Ajax to request Webapi under different domains, and return the results as shown

As you can see, the browser has actually made two requests.

Custom Policies

As you can see from the previous example, the list of domains (if wildcard characters are not used) is a static list that is compiled into the Web API code. While this may work in the development process or in certain situations, static lists are not sufficient if you need to dynamically determine the domain list or other permissions (for example, from a database).

We're going to introduce you tomorrow. Webapi Custom cross-domain policy, that is, the domain exists in the database or configuration file, the program can dynamically modify the allowed domain request ~ ~

ASP. NET Web API 2 support for 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.