user31823
user31823

Reputation: 149

ASP NET CORE - ANGULAR NO 'Access-Control-Allow-Origin' header is present on the requested resource

This question may be asked many times but the solutions available online are not working for me.

In our project we have as Asp.Net Page with the WebMethod that that handles database, or if I put it this way we have a WebApi as:-

http://server/Pages/ApplicationData.aspx/GetApplicationLookups

Now we have an AspNet Core Angular web application which calls that this API

postgetGetApplicationLookups(url: string) {
    var headers = new Headers();
    headers.set('Accept', 'application/json; charset=utf-8');
    headers.set('content-Type', 'application/json; charset=utf-8');
    let data = {};
    debugger;
    return this.http.post(
        url,
        data,
        { headers: headers }
    )
        .map(this.handleSuccess)
        .catch(this.handleError)
}

I get the following error:- ]

This POST Call works fine if I work with POSTMAN:-

I modified my Startup.cs with the following code but I am still getting the same error.

    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddCors(options => options.AddPolicy("AllowAll", p => p.AllowAnyOrigin()           //Fix API ISSUE
                                                                    .AllowAnyMethod()               //Fix API ISSUE
                                                                     .AllowAnyHeader()));           //Fix API ISSUE


        services.AddMvc();
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseWebpackDevMiddleware(new WebpackDevMiddlewareOptions
            {
                HotModuleReplacement = true
            });
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
        }

        app.UseStaticFiles();

        app.UseCors("AllowAll");        

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");

            routes.MapSpaFallbackRoute(
                name: "spa-fallback",
                defaults: new { controller = "Home", action = "Index" });
        });
    }

My error is :

Failed to load http://server/Pages/ApplicationData.aspx/GetApplicationLookups: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:60602' is therefore not allowed access.

Any ideas that what I may be missing.

Thanks

Upvotes: 6

Views: 10040

Answers (1)

R. Richards
R. Richards

Reputation: 25151

Order matters when adding things to the StartUp.cs.

In the ConfigureServices function, you need to have the AddMvc call after the AddCors call.

services.AddCors(options =>
{
    options.AddPolicy("AllowAll", p =>
    {
        p.AllowAnyOrigin()
        .AllowAnyHeader()
        .AllowAnyMethod();
    });
});
...
services.AddMvc(); // must be after AddCors

In the Configure function, just use one UseCors call:

app.UseCors("AllowAll");
app.UseMvc();

And, make sure that is called before the UseMvc call, too.

Upvotes: 17

Related Questions