Support for CORS in ASP. NET Web API 2 and apicors

Source: Internet
Author: User
Tags domain list

Support for CORS in ASP. NET Web API 2 and apicors

CORS Concept

Cross-origin Resource Sharing (CORS) is a World Wide Web Federation (W3C) specification (usually considered a part of HTML5) that allows JavaScript to overcome the same domain policy security restrictions imposed by browsers. The so-called same-domain policy means that JavaScript can only perform AJAX callback on the same domain that contains the webpage (the "Domain" is a combination of host names, protocols, and port numbers ). For example, JavaScript on a web page in a http://foo.com cannot make AJAX calls to a http://bar.com (or http://www.foo.com, https://foo.com, or http://foo.com: 999, etc.

CORS allows the server to specify which domains are allowed to call them, thus easing this restriction. CORS is enforced by the browser and must be implemented on the server. The latest version of ASP. NET Web API 2 fully supports CORS. Web API 2 allows you to configure policies to allow JavaScript clients in different domains to access your APIs.

CORS Basic Information

Since Web APIs are fully implemented in accordance with this specification, it is helpful to learn more about CORS in order to use the new CORS function in Web APIs. These details may seem to be theoretical, but they will be useful for you to understand the available settings of Web APIs in the future: When you debug CORS, this helps you solve problems more quickly.

The general mechanism of CORS is that when JavaScript tries to call cross-Origin AJAX, the browser will send a header (such as "Origin") in the HTTP request ") to "ask" whether the server allows such a call. The server returns an HTTP header (for example, "Access-Control-Allow-Origin") in the response to indicate the allowed operations. This permission check will be performed for each different URL called by the client, which means that different URLs can have different permissions.

Except for the domain, CORS also allows the server to specify the HTTP methods that can be used, HTTP request headers that can be sent by the client, HTTP Response Headers that can be read by the client, and whether the browser can automatically send or receive creden (Cookie or authorization) header ). Other request and Response Headers indicate which features are allowed.Figure 1Summarize these headers (note that some features do not have headers sent in the response, but only responses ).

Figure 1 cors http Header

Permission/Function Request Header Response Header
Domain Domain Access-Control-Allow-Origin
HTTP Method Access-Control-Request-Method Access-Control-Allow-Method
Request Header Access-Control-Request-Headers Access-Control-Allow-Headers
Response Header   Access-Control-Expose-Headers
Creden   Access-Control-Allow-Credentials
Cache precheck response   Access-Control-Max-Age

The browser can request these permissions to the server in two different ways: simple CORS requests and pre-check CORS requests.

 

Support for CORS in Web API 2

CORS support in Web APIs is a complete framework that allows applications to define the permissions of CORS requests. This framework is based on a policy scheme that allows you to specify the CORS function for any given request to access the application.

First, to obtain 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 the Microsoft. AspNet. WebApi. Cors package. Input in early nuget

Install-Package Microsoft.AspNet.WebApi.Cors

Note that for Web api 2, the net framework must have more than 4.5 requirements. After the preceding package is installed, two important packages are added to the reference, as shown in

 

To express this policy, Web API provides a custom attribute class named EnableCorsAttribute. This class contains attributes such as allowed domains, HTTP methods, request headers, response headers, and whether creden are allowed (they model all the details of the CORS specification described above ).

Finally, in order for the Web api cors framework to process CORS requests and issue appropriate CORS response headers, this class must check each request that enters the application. Web APIs Provide extensions for such interception operations through message processing programs. The Web api cors framework implements a message processing program named CorsMessageHandler. For CORS requests, the handler queries the policies expressed in the properties of the called method and sends out appropriate CORS response headers.

EnableCorsAttribute. The EnableCorsAttribute class is the way applications express their CORS policies. The EnableCorsAttribute class has an overloaded constructor that accepts three or four parameters. These parameters (in sequence) are:

There is also an attribute that allows the use of creden­ (Supports ­ Credentials) and another attribute that is used to specify the precheck cache duration value (PreflightMaxAge ).

 

Take the default api program created in vs2013 as an example. After the webapi reference program is created, two control zones, HomeController and ValueController, are automatically generated under the Controller folder. Let's take a look at ValueControll, this controller inherits ApiController. It can be seen that it is a webapi. we add a global EnableCors attribute on valueController to try to support cross-origin, as shown in

Note that each constructor parameter is a string. Multiple values can be expressed by specifying a comma-separated list. If you want to allow all domains, request headers, or HTTP methods, you can use "*" as the value (the Response Header must still be explicitly specified ).

In addition to applying the EnableCors attribute at the method level, you can also apply this attribute at the class level or apply it to applications globally. When this attribute is applied, CORS is configured for all requests of this level and below in the Web API code. For example, if this policy is applied at the method level, the policy applies only to the request of this operation. If this policy is applied at the class level, the policy applies to all requests to the Controller. Finally, if the policy is applied globally, the policy applies to all requests.

If a policy exists at multiple locations, the "nearest" attribute is used, and other attributes are ignored (methods, classes, and global attributes are prioritized ). If you have applied a policy at a higher level but want to exclude a request at a lower level, you can use another attribute class named DisableCorsAttribute. This attribute 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 options. First, you can explicitly specify the HTTP Method in the HTTP Method list. Alternatively, you can retain wildcards, but use the DisableCors attribute to exclude the Delete method.

CorsMessageHandler. You must enable CorsMessageHandler for the cors framework to intercept requests for evaluating CORS policies and issuing CORS response headers. Message Processing programs are usually enabled by calling the EnableCors Extension Method in the Web API configuration class of the application:

Public static class WebApiConfig {public static void Register (HttpConfiguration config) {// Web API configuration and service // Web API route config. mapHttpAttributeRoutes (); config. routes. mapHttpRoute (name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new {id = RouteParameter. optional}); // enable cross-origin config. enableCors ();}}

 

 

Enter http: // localhost: 19881/api/values in the browser and the following message appears, indicating that the weapi is available.

Next, we will test the cross-origin. Create a mvc application and set the port number to 19894.

The code for the home/index page is as follows:

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

  

The code is very simple. It prevents a button from being placed and uses ajax to request webapis in different domains. The returned results are shown in.

As you can see, the browser actually sent two requests.

 

Custom Policy

The preceding example shows that the domain list (if no wildcard is used) is a static list compiled into the Web API code. Although this may work during development or under specific circumstances, if you need to dynamically determine the domain list or other permissions (for example, obtained from the database ), the static list is not enough.

We will introduce you to the WebApi custom Cross-Domain Policy tomorrow, that is, to store the domain in a database or configuration file, and the program can dynamically modify the requests of the allowed domain ~~

 

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.