HTML   发布时间:2022-04-14  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了.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
    .
    .
    .
}

大佬总结

以上是大佬教程为你收集整理的.NET Web API CORS PreFlight请求全部内容,希望文章能够帮你解决.NET Web API CORS PreFlight请求所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。