c# - Web Api 2 CORS 不适用于 POST

标签 c# asp.net .net asp.net-web-api cors

根据 asp.net tutorial ,我们只需要以下代码即可在 Web Api 应用程序上启用 cors:

var cors = new EnableCorsAttribute("*","*", "*");
config.EnableCors(cors);

以下是我的代码:

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services  
        var cors = new EnableCorsAttribute("*","*", "*");
        config.EnableCors(cors);

        // Web API routes
        config.MapHttpAttributeRoutes();

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

        var jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().First();
        jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();

        config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
    }
}

它对 Get 工作正常,但对 Post 请求仍然出错

错误如下,我正在上Post:

POST http://api.example.com/token 404 (Not Found) XMLHttpRequest cannot load http://api.example.com/token. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://www.example.com' is therefore not allowed access. The response had HTTP status code 404.

最佳答案

您需要将以下内容添加到您的 Web.Config 中:

<httpProtocol>
   <customHeaders>
     <add name="Access-Control-Allow-Origin" value="*" />
     <add name="Access-Control-Allow-Headers" value="Content-Type" />
     <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
   </customHeaders>
</httpProtocol>

System.webServer 配置节点内部。

关于c# - Web Api 2 CORS 不适用于 POST,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32187006/

相关文章:

c# - 应该在属性上使用同步时钟吗?

css - 在模态对话框中设置文本框控件的大小

c# - vb.net asp.net webforms 应用程序 > c# asp.net mvc razor 应用程序

.net - Visual Basic 和命名空间问题

.net - 如何重复行值

c# - 如果没有连接 USB 电缆,则无法使 TCP 客户端代码工作

c# - 尽管 TransactionScopeOption.Suppress 嵌套事务回滚

c# - 使用 Web 窗体的 ASP.NET 路由

c# - ASP.NET 到 HTML5 localStorage

c# - 如何将MultiMap .Net转发到Java?