I have an ASP.NET Web API 2 app (hosted in Azure) and a front-end in Angular JS. When I try to call any of my controller methods I am getting the following error:
XMLHttpRequest cannot load https://........ No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. This is how my Configuration code looks in the Startup class.
public void Configuration(IAppBuilder app) { // setup cors policy var corsPolicy = new CorsPolicy { AllowAnyOrigin = true, //AllowAnyHeader = true, //AllowAnyMethod = true,
SupportsCredentials = true };
// add headers
foreach (var hdr in new string[] { "Authorization", "Content-Type", "Origin", "X-Requested-With", "Accept", "Cache-Control" }) { corsPolicy.Headers.Add(hdr); }
// add methods
foreach (var mth in new string[] { "GET", "POST", "PUT", "DELETE", "OPTIONS" }) { corsPolicy.Methods.Add(mth); }
// add origins
var allowedOrigins = ConfigurationManager.AppSettings["AllowedOrigins"];
if (allowedOrigins != null)
{
var origins = allowedOrigins.Split(',').Select(x => x.Trim());
if (origins.Any())
{
if (!origins.Contains("*"))
{
corsPolicy.AllowAnyOrigin = false;
// add each whitelisted origin
foreach (var origin in origins) { corsPolicy.Origins.Add(origin); }
}
}
}
// setup cors options
var corsOptions = new CorsOptions
{
PolicyProvider = new CorsPolicyProvider { PolicyResolver = context => Task.FromResult(corsPolicy) }
};
// enable cors
app.UseCors(corsOptions);
// setup JWT tokens auth
ConfigureOAuthTokenGeneration(app);
ConfigureOAuthTokenConsumption(app);
var httpConfig = new HttpConfiguration();
ConfigureWebApi(httpConfig);
app.UseWebApi(httpConfig);
}
Aucun commentaire:
Enregistrer un commentaire