.NET Web API CORS PreFlight请求

Mil*_*anG 16 .net cors http-delete preflight

我在向其他域上的Web API发出PUT和DELETE CORS请求时遇到一些麻烦.

我已经通过http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api#create-webapi-project教程对API进行了编码.

GET和POST请求工作正常,但DELETE和PUT没有.我收到这条消息:

Failed to load resource: the server responded with a status of 405 (Method Not Allowed)
Failed to load resource: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Run Code Online (Sandbox Code Playgroud)

当我在使用ASP.NET Web API的CORS支持PUT和DELETE时向WebConfig添加代码时,我只得到第一个错误.

有人可以帮我这个吗?

MCu*_*elo 28

您可以添加处理程序来处理此类请求.

创建一个派生自"DelegatingHandler"的类:

public class PreflightRequestsHandler : DelegatingHandler
{
    protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        if (request.Headers.Contains("Origin") && request.Method.Method.Equals("OPTIONS"))
        {
            var response = new HttpResponseMessage { StatusCode = HttpStatusCode.OK };
            // Define and add values to variables: origins, headers, methods (can be global)               
            response.Headers.Add("Access-Control-Allow-Origin", origins);
            response.Headers.Add("Access-Control-Allow-Headers", headers);
            response.Headers.Add("Access-Control-Allow-Methods", methods);
            var tsc = new TaskCompletionSource<HttpResponseMessage>();
            tsc.SetResult(response);
            return tsc.Task;
        }
        return base.SendAsync(request, cancellationToken);
    }

}
Run Code Online (Sandbox Code Playgroud)

稍后在Register方法的WebApiconfig.cs中添加:

public static void Register(HttpConfiguration config)
{
    // Define and add values to variables: origins, headers, methods (can be global) 
    // Enable global CORS
    config.EnableCors(new EnableCorsAttribute(origins, headers, methods));

    // Add handler to deal with preflight requests, this is the important part
    config.MessageHandlers.Add(new PreflightRequestsHandler()); // Defined above
    .
    .
    .
}
Run Code Online (Sandbox Code Playgroud)

  • 有趣的是,这个处理程序不会被Chrome调用.O_O (3认同)

Dom*_*nik 5

您对 Web API 执行的 AJAX 调用将触发预检检查(HTTP 动词“OPTIONS”)。这需要由您的系统处理,否则您将收到 405 错误。这里有一些关于如何做到这一点的答案,例如:

处理对 ASP.NET MVC 操作的 CORS 预检请求

如果您遵循以下准则,您也可以完全避免此飞行前通话。

The browser can skip the preflight request if the following conditions are true:

The request method is GET, HEAD, or POST, **and**
The application does not set any request headers other than Accept, Accept-Language, Content-Language, Content-Type, or Last-Event-ID, **and**
The Content-Type header (if set) is one of the following:
 - application/x-www-form-urlencoded
 - multipart/form-data
 - text/plain
Run Code Online (Sandbox Code Playgroud)

摘自http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api(在“预检请求”下):