问题
学习老杨的英语网站项目,运行项目时,发现出现了跨域的问题。
然后自己建一项目,进行配置,测试,发现配置CORS 跨域时,发现跨域的配置无效,依旧报错。
解决
网上找了一天,然后去翻老杨的视频,发现是因为 app.UseCors() 放在 app.UseHttpsRedirection() 的后面。
焯!配置的时候网上找的,都是放在app.UseHttpsRedirection() 的后面,后面去微软官方看教程也是放在后面。
解决
- app.UseCors() 要放在 app.UseHttpsRedirection() 之前
- 放在 app.UseRouting() 之后
- app.UseAuthorization() 之前
标题跨域测试
通过浏览器进行测试,咋样方便不用搞一个前端项目。
放在Console 里 直接回车。
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);
}
配置
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();