We are working on an application that has a mobile interface and a web interface. The web interface uses angular, and we are having problems setting up the cors on the server. Our code looks like this (only the code that is important for our problem):
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { app.UseCors("AllowAll"); app.UseMvc(); } public void ConfigureServices(IServiceCollection services) { services.AddMvc();
From a document and another post in stackoverflow, this should work, but no. What did we miss?
Thnx
EDIT:
This is the POSTMAN request:
curl ' https://guw.azurewebsites.net/api/token ' -X OPTIONS -H 'Pragma: no-cache' -H 'Access-Control-Request-Method: POST' -H 'Origin: http: // localhost: 9000 '-H' Accept-Encoding: gzip, deflate, sdch, br '-H' Accept-Language: en-US, en; q = 0.8 '-H' User-Agent: Mozilla / 5.0 (Windows NT 10.0; WOW64) AppleWebKit / 537.36 (KHTML, like Gecko) Chrome / 51.0.2704.103 Safari / 537.36 '-H' Accept: / '- H' Cache-Control: no-cache '-H' Referer: http: // localhost: 9000 / '-H' Connection: keep-alive '-H' Access-Control-Request-Headers: accept, authorization, content type ' - compressed
You can import it at the postman and look at it. This request is sent to angular.
Hope this helps.
In the end, I decided to add this method to my middleware:
private void AddCors(HttpContext context) { context.Response.Headers.Add("Access-Control-Allow-Headers", new string[] { "Authorization", "Content-Type" }); context.Response.Headers.Add("Access-Control-Allow-Methods", new string[] { "OPTIONS", "POST", "GET", "DELETE", "PUT" }); IEnumerable<string> allowedUrls = new List<string>() { "http://localhost:8100", "http://localhost:9000" }; if (allowedUrls.Count() > 0) { foreach(string x in allowedUrls) { var origin = context.Request.Headers.FirstOrDefault( key => key.Key == "Origin"); var found = x.ToLower() == origin.Value.ToString().ToLower(); if (found) { context.Response.Headers.Add("Access-Control-Allow-Origin", new string[] { origin.Value }); } } } return; }
EDIT:
This was fine, but in logic it didn't work as I needed, so I ended up with this in my middleware class, and it works great:
// Add CORS to every response context.Response.Headers.Add("Access-Control-Allow-Headers", new string[] { "Authorization", "Content-Type" }); context.Response.Headers.Add("Access-Control-Allow-Methods", new string[] { "OPTIONS", "POST", "GET", "DELETE", "PUT" }); context.Response.Headers.Add("Access-Control-Allow-Origin", "*"); if (context.Request.Method.Equals("OPTIONS", StringComparison.Ordinal)) { context.Response.StatusCode = 204; return _next(context); }
THX