0

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;
    }
}
Carlos
  • 1,638
  • 5
  • 21
  • 39
  • Did you added 'config.EnableCors();' in the WebApiConfig? see https://learn.microsoft.com/en-us/aspnet/web-api/overview/security/enabling-cross-origin-requests-in-web-api#enable-cors – nmbrphi Feb 06 '19 at 09:23
  • Yes, I did. In fact it works with all the others methods, this is the only one that throws cors errors. I update the question with the code in WebApiConfig. Thanks – Carlos Feb 06 '19 at 09:32
  • any particular reason you added a specific CORS attribute on that new method, even though you already defined it globally? Does it work if you get rid of that attribute and just rely on the global setting? – ADyson Feb 06 '19 at 09:40
  • @ADyson I added it because it did not work without it... and it does not work now with it too. No particular reason, just an experiment :) thanks – Carlos Feb 06 '19 at 09:47
  • " it did not work without it... and it does not work now with it too" ...so you mean once you added it, it started to work, but then later it stopped working again? In that case, what changed in between those two things? Things don't just stop working for no reason. – ADyson Feb 06 '19 at 10:07
  • sorry @CarlosAdrian but I didn't understand why you EnableCors in your method 'SePuedeServirPorAgencia', if you already did it globally in the WebApiConf... – nmbrphi Feb 06 '19 at 10:07
  • It does not work with or without the EnableCors in the method. It never has worked this method from a different domain (it only works in my local machine). I can remove the line if you want, as it does not affect in any way. Thanks – Carlos Feb 06 '19 at 10:19
  • 1
    @CarlosAdrian did you see this question https://stackoverflow.com/questions/18619656/enable-cors-in-web-api-2? Have you already tried the different solutions? – nmbrphi Feb 06 '19 at 10:25
  • @nmbrphi I am going to try all of these solutions. I am nearly sure it depends only on the route, in one method it is explicit and in the other it is convention based. I will tell you when I have tried the different solutions. Thanks – Carlos Feb 06 '19 at 10:36

1 Answers1

0

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

Carlos
  • 1,638
  • 5
  • 21
  • 39