具有多个 HttpPost 方法的 Web Api 中的 CORS 问题

Posted

技术标签:

【中文标题】具有多个 HttpPost 方法的 Web Api 中的 CORS 问题【英文标题】:CORS trouble in Web Api with multiple HttpPost methods 【发布时间】:2019-06-30 04:44:06 【问题描述】:

我有一个使用默认 WebApi 模板创建的控制器。它创建了一个这样的 post 方法:

    // POST: api/PedidosVenta
    [HttpPost]
    [ResponseType(typeof(PedidoVentaDTO))]
    public async Task<IHttpActionResult> PostPedidoVenta(PedidoVentaDTO pedido)

此时,CORS 在我的计算机和不同域中都可以正常工作。然后我需要使用不同路线的第二个 post 方法,并以这种方式创建它:

    [HttpPost]
    [EnableCors(origins: "*", headers: "*", methods: "POST")]
    [Route("api/PedidosVenta/SePuedeServirPorAgencia")]
    public async Task<RespuestaAgencia> SePuedeServirPorAgencia(PedidoVentaDTO pedido)

即使我调用此方法,它在我的计算机上也可以正常工作,但是当我尝试从不同的域运行时,它会引发 CORS 错误(仅当我调用此方法时,所有其他的都可以正常工作)。

我无法解决它,所以我确定我错过了一些重要的东西。谁能帮我用这种方法正确配置cors?

谢谢

更新:我粘贴了 WebApiConfig 的代码:

public static class WebApiConfig

    public static void Register(HttpConfiguration config)
    
        config.MapHttpAttributeRoutes();

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

        config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize;
        config.Formatters.JsonFormatter.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;

        config.Formatters.Remove(GlobalConfiguration.Configuration.Formatters.XmlFormatter);

        var cors = new System.Web.Http.Cors.EnableCorsAttribute(
        origins: "*",
        headers: "*",
        methods: "*");
        config.EnableCors(cors);

        GlobalConfiguration.Configuration.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;
    

【问题讨论】:

你添加了 'config.EnableCors();'在 WebApiConfig 中?见docs.microsoft.com/en-us/aspnet/web-api/overview/security/… 是的,我做到了。事实上,它适用于所有其他方法,这是唯一会引发 cors 错误的方法。我用 WebApiConfig 中的代码更新了这个问题。谢谢 您在该新方法上添加特定 CORS 属性的任何特殊原因,即使您已经在全局范围内定义了它?如果您摆脱该属性并仅依赖全局设置,它会起作用吗? @ADyson 我添加了它,因为没有它它就无法工作......而且它现在也无法使用它。没有特别的原因,只是一个实验:) 谢谢 @CarlosAdrian 你看到这个问题了吗***.com/questions/18619656/enable-cors-in-web-api-2?您是否已经尝试过不同的解决方案? 【参考方案1】:

global.asax 中的这段代码成功了:

protected void Application_BeginRequest(object sender,EventArgs e)

    HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
    if(HttpContext.Current.Request.HttpMethod == "OPTIONS")
    
        HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
        HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
        HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000" );
        HttpContext.Current.Response.End();
    

来自405 method options not allowed in asp.net web api controller?

然后我还必须从 WebApiConfig.cs 中删除 CORS,因为它是重复的并且给出了另一个错误:The 'Access-Control-Allow-Origin' header contains multiple values '*, *', but only one is allowed

【讨论】:

以上是关于具有多个 HttpPost 方法的 Web Api 中的 CORS 问题的主要内容,如果未能解决你的问题,请参考以下文章