Home > Web Front-end > JS Tutorial > How to implement WebApi Ajax cross-domain requests using CORS

How to implement WebApi Ajax cross-domain requests using CORS

php中世界最好的语言
Release: 2018-03-31 10:34:30
Original
2235 people have browsed it

This time I will bring you the method of using CORS to implement WebApi Ajax cross-domain requests. What are the precautions for using CORS to implement WebApi Ajax cross-domain requests. The following is a practical case, let's take a look.

Overview

Everyone who has used ASP.NET Web API knows how easy it is to use. There are no complicated configuration files , a simple ApiController plus the required Action will work. However, when using APIs, you will always encounter the problem of cross-domain requests. Especially today with the proliferation of various APPs, cross-domain requests for APIs are unavoidable.

By default, in order to prevent CSRF cross-site forgery attacks (or javascript's Same-Origin Policy), when a web page obtains data from another domain There will be restrictions. There are some ways to break through this limitation, which is the well-known JSONP. Of course, this is just one of many solutions. Since JSONP only supports GET requests, it can no longer meet the needs of today's complex businesses. CORS (Cross Origin Resource Sharing https://www.w3.org/wiki/CORS) cross-domain resource sharing is a new header specification that allows the server to relax cross-domain restrictions and switch restrictions based on headers. Or don't restrict cross-domain requests. The important thing is that it supports all http request methods.

Problem

XMLHttpRequest cross-domain POST or GET request, the request method will automatically become an OPTIONS problem.

Due to the existence of the CORS (cross origin resource share) specification, the browser will first send an options sniff, and at the same time bring the origin in the header to determine whether there is cross-domain request permission. The server responds with the value of access control allow origin. , for the browser to match the origin. If it matches, the post request will be officially sent. Even if the server allows the program to access cross-domain, if the options request is not supported, the request will die.

Reason

For the sake of security, the browser will use the transparent server verification mechanism of Preflighted Request to support developers to use custom headers, GET Or methods other than POST, and different types of subject content, that is, an options request will be sent first,
Ask the server whether the request will be correct (allowed) to ensure that the request is safe to send.

The situations where OPTIONS appear are generally:

1. Non-GET, POST request

2. The content-type of POST request is not the conventional three: application/x- www-form-urlencoded (form submitted using HTTP POST method), multipart/form-data (same as above, but mainly used when form submission is accompanied by file upload), text/plain (plain text )

3. The payload of the POST request is text/html

4. Set custom headers

OPTIONS request headers will include the following headers: Origin, Access -Control-Request-Method, Access-Control-Request-Headers. After sending this request, the server can set the following headers to communicate with the browser to determine whether to allow the request.
Access-Control-Allow-Origin, Access-Control-Allow-Method, Access-Control-Allow-Headers

Solution

This method is powerful and can solve complex cross-domain requests of ASP.NET Web API, carrying complex header information, body content and authorization verification 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);
 }
}
Copy after login

How to use, add

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());
}
Copy after login

Method 2

Add the following configuration to the configuration file in the Global.asax file. This method is simple and can handle simple cross-domain requests

<system.webServer>
 <httpProtocol>
  <customHeaders>
  <add name="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>
 </httpProtocol>
<system.webServer>
Copy after login

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

How to convert entity classes and xml files

Detailed explanation of the method of Ajax partial update of Razor page

The above is the detailed content of How to implement WebApi Ajax cross-domain requests using CORS. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template