简体   繁体   中英

CORS trouble in Web Api with multiple HttpPost methods

I have a controller created with the default WebApi template. It creates one post method like this:

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

At this time CORS was working fine from my computer and from different domains. Then I needed a second post method with a different route and I created it this way:

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

It works fine in my computer, even when I call this method, but when I try to run from a different domain, it throws CORS errors (only when I call this method, all the other ones work fine).

I am not able to solve it, so I am sure I am missing something important. Can anyone help me to config cors properly in this method, please?

Thank you

UPDATE: I paste the code of 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;
    }
}

This code in global.asax did the trick:

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();
    }
}

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

Then I also had to remove CORS from WebApiConfig.cs, because it was duplicate and gave another error: The 'Access-Control-Allow-Origin' header contains multiple values '*, *', but only one is allowed

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM