1

Im writing a little service using c#(.net framework) and odata V4. My clientside is AngularJs. On my localhost everythink works fine, but when Im releasing my code to the server(widows server 2012 R2) I got cors problems. I tried different solutions:

  1. Tried to put Access-Control-Allow-Origin,Access-Control-Allow-Headers,Access-Control-Allow-Methods,Access-Control-Allow-Credentials at web.config, got 401 and 500 response preflight.

  2. add CorsHandler class to handle the preflight/add Application_BeginRequest to handle it as well, no luck (return there the Access-Control-Allow-Origin and etc...). and stuff from here as well: Handling CORS Preflight requests to ASP.NET MVC actions

and finally tried the Microsoft.AspNet.WebApi.Cors package just like that:

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

And guess what, its no helping either!

When I send the POST method I have to send it with Content-Type:"x-www-form-urlencoded", because application/json triggers the preflight, and text/plain is not supported for some reason.I have an enpoint which use ODataActionParameters object, and its always null,assuming because of the content type of the urlencoded.

Hope Someone can help me, Im banging my head...

Elad Motola
  • 45
  • 10
  • contentType: 'application/json; charset=utf-8' normally works for me. – Brandon Miller Feb 27 '18 at 20:16
  • forgot to mention that im using angularjs, so the defult of $http post method header is that content type. i updated my question – Elad Motola Feb 27 '18 at 20:32
  • Try [this slightly different solution](https://forums.asp.net/t/2032931.aspx?How+to+enable+CORS+in+Odata+NET+service+) in your `Application_BeginRequest` method. It addresses explicitly `odata` requests. Also, check [this detailed info about CORS](https://msdn.microsoft.com/en-us/magazine/dn532203.aspx?f=255&MSPPError=-2147217396). – Diana Feb 27 '18 at 21:14

1 Answers1

0

After examining again Diana's link, I made it work. But I made changes. I return Access-Control-Allow-Origin and Access-Control-Allow-Credentials for every request, and if its OPTIONS request, I return the rest of the headers:

 protected void Application_BeginRequest()
            {
                Context.Response.AddHeader("Access-Control-Allow-Origin", ORIGINS);
                Context.Response.AddHeader("Access-Control-Allow-Credentials", "true");
                if (Context.Request.HttpMethod == "OPTIONS")
                {                    
                    Context.Response.AddHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
                    Context.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST PUT, DELETE, OPTIONS");                    
                    Context.Response.End();
                }
            }
Elad Motola
  • 45
  • 10