加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 资源网站 > 资源 > 正文

.NET Web API CORS PreFlight请求

发布时间:2020-12-14 18:50:58 所属栏目:资源 来源:网络整理
导读:我有麻烦使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不.我收到这个消息:
我有麻烦使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
    .
    .
    .
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读