Search code examples
c#asp.netangularcorscross-domain-policy

Call to my rest service from Angular app hosted in Asp.net core web server blocked by CORS policy


I have a Angular App that is hosted in Asp.net core web server, though this Angular app i am calling another Rest api service for getting some data but my call to external Rest Service api is blocked by CORS policy.

The Error i am getting in browser is -

enter image description here

and my Asp.net server application Startup.cs

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace WebclientServer
{
public class Startup
{
    // This method gets called by the runtime. Use this method to add services to the container.
    // For more information on how to configure your application, visit 
    https://go.microsoft.com/fwlink/?LinkID=398940
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddCors(options =>
        {
          options.AddPolicy("CorsPolicy",
              builder => builder.AllowAnyOrigin()
                  .AllowAnyMethod()
                  .AllowAnyHeader());
        });
        services.AddMvc();

    }

    // This method gets called by the runtime. Use this method to configure the HTTP request 
    pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        //if (env.IsDevelopment())
        //{
        //    app.UseDeveloperExceptionPage();
        //}

        //app.UseRouting();

        //app.UseEndpoints(endpoints =>
        //{
        //    endpoints.MapGet("/", async context =>
        //    {
        //        await context.Response.WriteAsync("Hello World!");
        //    });
        //});

        app.UseCors("CorsPolicy");

        app.Use(async (context, next) => {
            await next();
            if (context.Response.StatusCode == 404 &&
               !Path.HasExtension(context.Request.Path.Value) &&
               !context.Request.Path.Value.StartsWith("/api/"))
            {
                context.Request.Path = "/index.html";
                await next();
            }
        });
        //app.UseMvcWithDefaultRoute();
        app.UseDefaultFiles();
        app.UseStaticFiles();
    }
  }
}

I have read about how to solve this error on internet from this link How to enable CORS in ASP.net Core WebAPI but no sucess in my case. Please dont mind i am new to web development stuff, and on CORS policy error i am already stuck for days. Please help on how can i solve this error. Also do i have to enable CORS on my External Rest api service. Thanks!


Solution

  • CORS is a server side "problem", not client. So, I guess, you should not try to fix it on your client (i.e., Angular even if it is hosted on X server-type). That's why, I think, your ASP.net fix is not working. Trying to fix CORS on client-side, although sometimes possible, most times leads to errors or just the server ignoring/blocking the requests.

    The simpliest approach is to configure CORS on your server side. You've specified that you are accessing an External REST API. Thus, there is where you have to dig in, and forget client fixes.