概念理解
CORS:跨域资源共享
简单请求
非简单请求
一图说明
手动尝试
客户端
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
</head>
<script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
<body>
<h1>这是标题</h1>
<button onclick="SendCors1()">SendCORS !! </button>
<script>
function SendCors1() {
$.ajax({
url: 'https://localhost:7178/home/',
method: 'GET',
headers:{
'aa':'3232' //自定义的header表示为非简单请求
},
success: (res) => {
console.warn('success', res);
alert(res.content);
}
});
}
</script>
</body>
</html>
服务端
var builder = WebApplication.CreateBuilder(args);
// 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();
//步骤一
//CORS配置
string pname = "testpolicy";
builder.Services.AddCors(options =>
{
options.AddPolicy(name: pname,
policy =>
{
policy.AllowAnyHeader().AllowAnyOrigin();
});
});
var app = builder.Build();
//...
//步骤二
//使用跨域资源共享
app.UseCors(pname);
app.MapControllers();
app.Run();
http请求示例
参考
阮一峰-跨域资源共享 CORS 详解 MDN-跨源资源共享(CORS) fetch 在 ASP.NET Core 中启用跨源请求 (CORS) Getting started with the IIS CORS Module