CORS-based WebApi Ajax cross-origin request solution, corswebapi

Source: Internet
Author: User

CORS-based WebApi Ajax cross-origin request solution, corswebapi

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. In particular, the cross-origin requests of Apis 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 businesses cannot meet their needs. CORS (Cross Origin Resource Sharing https://www.w3.org/wiki/CORS) Cross-Origin Resource Sharing is a new header specification that allows the server to relax the Cross-Origin restrictions, you can use the header to switch between limits or do not limit 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 for the browser to match with the origin. If the origin matches, the server formally sends a post request. Even if the server permits cross-origin access by the program, if the options request is not supported, the request will also die.

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

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.

Method 1

public class CrosHandler:DelegatingHandler{ private const string Origin = "Origin"; private const string AccessControlRequestMethod = "Access-Control-Request-Method"; private const string AccessControlRequestHeaders = "Access-Control-Request-Headers"; private const string AccessControlAllowOrign = "Access-Control-Allow-Origin"; private const string AccessControlAllowMethods = "Access-Control-Allow-Methods"; private const string AccessControlAllowHeaders = "Access-Control-Allow-Headers"; private const string AccessControlAllowCredentials = "Access-Control-Allow-Credentials"; protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) {  bool isCrosRequest = request.Headers.Contains(Origin);  bool isPrefilightRequest = request.Method == HttpMethod.Options;  if (isCrosRequest)  {   Task<HttpResponseMessage> taskResult = null;   if (isPrefilightRequest)   {    taskResult = Task.Factory.StartNew<HttpResponseMessage>(() =>    {     HttpResponseMessage response = new HttpResponseMessage(System.Net.HttpStatusCode.OK);     response.Headers.Add(AccessControlAllowOrign,      request.Headers.GetValues(Origin).FirstOrDefault());     string method = request.Headers.GetValues(AccessControlRequestMethod).FirstOrDefault();     if (method != null)     {      response.Headers.Add(AccessControlAllowMethods, method);     }     string headers = string.Join(", ", request.Headers.GetValues(AccessControlRequestHeaders));     if (!string.IsNullOrWhiteSpace(headers))     {      response.Headers.Add(AccessControlAllowHeaders, headers);     }     response.Headers.Add(AccessControlAllowCredentials, "true");     return response;    }, cancellationToken);   }   else   {    taskResult = base.SendAsync(request, cancellationToken).ContinueWith<HttpResponseMessage>(t =>    {     var response = t.Result;     response.Headers.Add(AccessControlAllowOrign,      request.Headers.GetValues(Origin).FirstOrDefault());     response.Headers.Add(AccessControlAllowCredentials, "true");     return response;    });   }   return taskResult;  }  return base.SendAsync(request, cancellationToken); }}

In the Global. asax File

protected void Application_Start(){ IOCConfig.RegisterAll(); AreaRegistration.RegisterAllAreas(); WebApiConfig.Register(GlobalConfiguration.Configuration); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); GlobalConfiguration.Configuration.MessageHandlers.Add(new CrosHandler());}

Method 2

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

<system.webServer> 

Summary

The above is a small series of cross-origin request solutions for implementing WebApi Ajax Based on CORS. I hope it will be helpful to you. If you have any questions, please leave a message for me, the editor will reply to you in a timely manner. Thank you very much for your support for the help House website!

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.