question
Learning Lao Yang's English website project, when running the project, I found a cross-domain problem.
Then build a project by yourself, configure, test, and find that when configuring CORS cross-domain, it is found that the cross-domain configuration is invalid, and an error is still reported.
solve
I searched the Internet for a day, and then went to Lao Yang's video, and found that it was because app.UseCors() was placed behind app.UseHttpsRedirection().
Zhuo! When configuring, I found it on the Internet, and they were all placed behind app.UseHttpsRedirection(), and I went to Microsoft to read the official tutorial later.
solve
- app.UseCors() should be placed before app.UseHttpsRedirection()
- After app.UseRouting()
- before app.UseAuthorization()
Title cross domain test
Testing through a browser is so convenient that you don't need to build a front-end project.
Put it in the Console and press Enter directly.
var xhr = new XMLHttpRequest();
xhr.open('POST', 'http://localhost/IdentityService/Login/LoginByUserNameAndPwd');
xhr.setRequestHeader("Content-type","application/json;charset=UTF-8");
xhr.setRequestHeader("jwt-token","JhbGciOiJSUzI1N");
xhr.send('{
"userName":"cc0c","password":"ddd"}');
xhr.onload = function(e) {
var xhr = e.target;
console.log(xhr.responseText);
}
configuration
using HttpTest;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using Microsoft.Net.Http.Headers;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddCors(options =>
{
options.AddPolicy("Policy1",
policy =>
{
policy.WithOrigins("https://www.baidu.com", "http://localhost:4173").AllowAnyMethod()
.AllowAnyHeader().AllowCredentials();
});
});
builder.Services.Configure<MvcOptions>(opt =>
{
opt.Filters.Add<FilterOne>();
});
// Add services to the container.
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
app.UseRouting();
app.UseCors("Policy1");
app.UseHttpsRedirection();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseAuthorization();
app.MapControllers();
app.Run();