1
votes

I have created an ASP.NET Core 1.1 Web API which is consumed by an Angular2 (IONIC) app. At the beginning of the project, we were getting CORS errors, which, after some modifications to the Web API, we were able to resolve. This morning I updated our live Web API with some changes I made over the past week and for some reason or other, we are getting the CORS error again (when the Angular app consumes the live Web API - it works fine with we connect to the Web API running on my localhost from another PC on the LAN). The error is:

XMLHttpRequest cannot load http://inspections.propworx.co.za/api/inspections. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://192.168.1.100:8100' is therefore not allowed access.

I have the following in my Web API Startup.cs:

public void ConfigureServices(IServiceCollection services)
{
    services.AddCors(options =>
    {
        options.AddPolicy("SiteCorsPolicy",
        builder => builder.AllowAnyOrigin()
        .AllowAnyMethod()
        .AllowAnyHeader()
        .AllowCredentials());
    });
    ...
}

and this:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    app.UseCors("SiteCorsPolicy");
    ...
}

In both cases, they are before the services.AddMvc() and app.UseMvc respectively. But it still doesn't work. I have tried adding

services.Configure<MvcOptions>(options =>
{
    options.Filters.Add(new CorsAuthorizationFilterFactory("SiteCorsPolicy"));
});

in ConfigureServices, just after services.AddCors, to no avail. I have tried adding:

[EnableCors("SiteCorsPolicy")]

to the top of my controllers, but also didn't help.

This was working, and I don't know what I couldve done but it's not working now :/ Any ideas anyone? Thanks...

2
Hi user1900799 , i have a question i want to know when creating ionic app that consumes WebApi service should i put the Ionic project in the same folder as the Web Api project or the two project are separated???Haytham

2 Answers

1
votes

There problem was that there was no Web.config file... ASP.Net Core doesnt seem to generate one for Web API's, but this is needed for CORS...

0
votes

I ran into a similar issue a few days back, and here is how I have fixed it. While calling web API from angular please make sure to add below headers.

let headers = new Headers({'Content-Type': 'application/json'});
headers.append('Access-Control-Allow-Origin', '*');
headers.append('Accept', 'application/json');