Issue
I get this error: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://localhost:7218/api/User/Login. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing). Status code: 404.
Angular:
public headers = new HttpHeaders()
.set('content-type', 'application/text')
.set('Access-Control-Allow-Origin', '*');
Login(){
this.http.options("https://localhost:7218/api", {headers: this.headers})
this.http.post("https://localhost:7218/api/User/Login", new LoginDto(this.login, this.password), {
headers: this.headers
}).subscribe(response => console.log(response))
}
C#:
builder.Services.AddCors(options =>
{
options.AddPolicy(name: "localhost",
policy =>
{
policy.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod();
});
});
builder.Services.AddResponseCaching();
builder.Services.AddDataProtection();
builder.Services.AddControllers();
builder.Services.AddDbContext<DataBaseContext>(options =>
options.UseMySql(config.GetConnectionString("DbConnection"), ServerVersion.AutoDetect(config.GetConnectionString("DbConnection")))
);
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddSingleton<ISessionMiddleware, SessionMiddleware>();
builder.Services.AddTransient<IUserService, UserService>();
builder.Services.AddTransient<IProductService, ProductService>();
builder.Services.AddTransient<IActionHistoryService, ActionHistoryService>();
var app = builder.Build();
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers().RequireCors("localhost");
});
app.UseStaticFiles();
app.UseCors("localhost");
I tried adding headers to angular, to the post request, to the options request, content-type/json, nothing works
Solution
I tried this problem with a real project. There are two issues here. One CORS error and one 404 error. If the only issue with your code was CORS, you shouldn't have gotten a 404 (not found) error.
Regarding the 404 error, maybe the issue is with the URL in the client fetch or routing in ASP. Due to your limited information, it is not possible to say exactly where the issue is. However, this issue is usually not difficult to solve.
But in the case of CORS, according to Microsoft's official document, your issue is the order of middlewares. Update your code like this:
app.UseStaticFiles();
app.UseRouting();
app.UseCors("localhost");
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers().RequireCors("localhost");
});
I hope it was useful.
Answered By - Hamid Molareza
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.