.NET Web API CORS PreFlight请求

 你一句话就逼我撤退 发布于 2023-02-07 23:38

我在向其他域上的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.

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

有人可以帮我这个吗?

1 个回答
  • 您可以添加处理程序来处理此类请求.

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

    稍后在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
        .
        .
        .
    }
    

    2023-02-07 23:48 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有