Reputation: 3417
This is my Program.cs
file:
using BackendTemplate.Utils;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using System.Text;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddAuthorization();
builder.Services.AddCors(o => o.AddPolicy("MyPolicy", builder =>
{
builder.WithOrigins("*")
.AllowAnyMethod()
.AllowAnyHeader()
.AllowAnyOrigin();
}));
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseCors("MyPolicy");
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();
This is my controller
[HttpPost]
public ApiResponse<string> Post([FromBody] UsrUser user)
{
// .....
}
Only the POST
generates a CORS error; the GET
works correctly.
This is my error on Angular console:
Access to XMLHttpRequest at 'https://mydns/api/login' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
I cannot understand how to solve this problem, is the first time this happens to me.
Upvotes: 2
Views: 320
Reputation: 160
This is not .NET 8's fault, there were multiple questions years before .NET 8 is released (ok some questions are related to .NET 8 but it's innocent):
The root cause is CORS preflight request.
Some answers involved JSONP but I chose the simplest solution: skip the preflight request.
You can edit your request so that the browser will not send preflight request, according to the docs:
Upvotes: 0