Web API CORS support for application/json content type

Suppose a simple architecture is divided into two parts, one is the front-end page site composed of Angular, and the other is the back-end service site built through ASP.NET Web API. Because the two sites are deployed separately, there will be CORS (Cross-Origin Resource Sharing) problems.

Then assume that the backend has been configured accordingly, such as adding in web.config:

  <httpProtocol>
    <customHeaders>
      <add name="Access-Control-Allow-Origin" value="*" />
      <add name="Access-Control-Allow-Methods" value="GET, PUT, POST, DELETE, HEAD" />
      <add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept" />
    </customHeaders>
  </httpProtocol>

Then the front-end calls the back-end interface:

  save(data: any) : Observable<any> {
      return this.http.post(`${this.apiUrl}`, data)
  }

In theory, the logic in the corresponding interface of the backend should be able to be executed normally:

  [HttpPost]
  [Route("api/save")]
  public HttpResponseMessage Save(SomeModel model)
  {
      //内部逻辑
  }

But the result is an Message:"The requested resource does not support http method 'OPTIONS'."error.

The reason for this problem is that the post method of HttpClient adopts the content type (Content-Type) of application/json by default.

And there are two types in the CORS specification:

  • Simple requests
  • Preflighted requests

The former requires no additional processing, but the support for content types is limited to three:

  • application/x-www-form-urlencoded
  • multipart/form-data
  • text/plain

For other content types, such as application/json, CORS will be processed as Preflighted requests.

Preflighted requests require that a preflight request must first be initiated to the server using the OPTIONS method to know whether the server allows the actual request.

In the above back-end service code, there is no corresponding interface for processing OPTIONS requests, so there is such an error.

The corresponding correction method is very simple. Add the logic for processing the OPTIONS request to the same interface method:

  [HttpOptions, HttpPost]
  [Route("api/save")]
  public HttpResponseMessage Save(SomeModel model)
  {
      if (Request.Method == HttpMethod.Options) return new HttpResponseMessage(HttpStatusCode.OK);
      //内部逻辑
  }

For a detailed description of CORS, it is recommended to refer to the official document - Cross-Origin Resource Sharing (CORS)

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325168363&siteId=291194637