即使我启用了 cors,PUT 和 DELETE 请求也无法在 Web API 2 中工作

Posted

技术标签:

【中文标题】即使我启用了 cors,PUT 和 DELETE 请求也无法在 Web API 2 中工作【英文标题】:PUT and DELETE requets are not working in Web API 2 even I have enabled cors 【发布时间】:2016-12-02 20:52:45 【问题描述】:

我有一个 angularjs 网络应用程序。我已经在那里集成了这个 web api。获取并发布 请求正在工作,但是当我尝试放置和删除请求时,它给出了一个错误:

加载资源失败:服务器响应状态为 405(不允许方法) /#/Delete:1 XMLHttpRequest 无法加载http://abc.example.net/api/employees/3。请求的资源上不存在“Access-Control-Allow-Origin”标头。因此,Origin 'http://example.net' 不允许访问。响应的 HTTP 状态代码为 405。

我在 WebApiConfig 中编写了以下代码。

public static class WebApiConfig

    public static void Register(HttpConfiguration config)
    
        // Web API configuration and services
                 var cors = new EnableCorsAttribute("http://example.net", "*", "*");
                 config.EnableCors(cors);

        // Configure Web API to use only bearer token authentication.
                    config.SuppressDefaultHostAuthentication();
                    config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));

        // Web API routes
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/controller/id",
            defaults: new  id = RouteParameter.Optional 
        );
    

【问题讨论】:

【参考方案1】:

使用 DynamicPoliceProviderFactory 类将所有子域添加到 CORS 策略或将 EnableCorsAttribute 的第一个参数更改为 * 以允许所有 Origin。

【讨论】:

以上是关于即使我启用了 cors,PUT 和 DELETE 请求也无法在 Web API 2 中工作的主要内容,如果未能解决你的问题,请参考以下文章

Springboot 2.0.2 - 解决 PUT 和 DELETE 的 CORS

CORS 正在阻止 PUT、DELETE 和 POST 请求,但 GET 正在工作

AJAX POST、PUT 和 DELETE 工作正常,但 GET 被 CORS 阻止

使用 DELETE 获取 api 问题 - 即使 cors 很好,也会更改 OPTIONS

Chrome 的插件 CORS Toggle 无法使用 POST/PUT/DELETE 方法

无法在 JQuery 1.6.4 中使用 CORS 进行 PUT/POST/DELETE HTTP 调用