I have Asp.Net Core(3) WebApi project with UI based on Angular(7.2.1) on Client side. When using Postman or just using the URL I can use GET and POST without any particular errors. When trying the same by Angular(Chrome\FireFox\IE Browser) I'm getting the following errors.
zone.js:3243 OPTIONS http://localhost:8888/api/PaymentDetails 405 (Method Not Allowed)
ccess to XMLHttpRequest at 'http://localhost:8888/api/PaymentDetails' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
I'll try to share as much as code I can to demonstrate the flow.
WebApi Startup.cs:
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy("CorsPolicy",
builder =>
builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
);
});
services.AddControllers()
.AddJsonOptions(options =>
{
options.JsonSerializerOptions.PropertyNameCaseInsensitive = true;
options.JsonSerializerOptions.PropertyNamingPolicy = null;
});
services.AddDbContext<PaymentDetailContext>(options => options.UseSqlServer("Server=DESKTOP-KT0N2RN\\SQLEXPRESS;DataBase=PaymentDetailDB;Trusted_Connection=True;MultipleActiveResultSets=True;"));
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
app.UseCors("CorsPolicy");
}
WebAPi GET method:
[HttpGet]
public async Task<ActionResult<IEnumerable<PaymentDetail>>> GetPaymentDetails()
{
return await _context.PaymentDetails.ToListAsync();
}
Client Side:
rootUrl: string = "http://localhost:8888/api";
getPaymentDetail()
{
console.log(`${this.rootUrl}/PaymentDetails`)
const headers = new HttpHeaders().set('Content-Type','application/json');
// headers.append('Access-Control-Allow-Origin', '*');
// headers.append('Access-Control-Allow-Headers','Origin, X-Requested-With, Content-Type, Accept');
return this._http.get(`${this.rootUrl}/PaymentDetails`,{headers:headers});
}