.NET Web API CORS PreFlight请求

前端之家收集整理的这篇文章主要介绍了.NET Web API CORS PreFlight请求前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有麻烦使PUT和DELETE CORS请求到其他域上的Web API.

我已经通过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.

当我添加代码到WebConfig建议在CORS support for PUT and DELETE with ASP.NET Web API,我只得到第一个错误.

有人可以帮我吗

解决方法

您可以添加一个处理程序来处理这种类型的请求.

创建一个派生自“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);
    }

}

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

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

    // Add handler to deal with preflight requests,this is the important part
    config.MessageHandlers.Add(new PreflightRequestsHandler()); // Defined above
    .
    .
    .
}
原文链接:https://www.f2er.com/html/224992.html

猜你在找的HTML相关文章