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 -
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!