1.首先在startup页面中 ConfigureServices中创建跨域规则名称为
“cors”
// 配置跨域处理,允许所有来源
services.AddCors(options =>
options.AddPolicy("cors",
p => p.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod().AllowCredentials()));
其中指定对应的域名来的源是:
//允许一个或多个来源可以跨域
services.AddCors(options =>
{
options.AddPolicy("CustomCorsPolicy", policy =>
{
// 设定允许跨域的来源,有多个可以用','隔开
policy.WithOrigins("http://localhost:21632", "http://localhost:24661")
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials();
});
});
2.将跨域规则写入全局配置中(Configure)
(我好像这里配了也没有起到作用,所以有了第三配置方式)
app.UseCors("cors");
也可以直接把规则写在 configure中
// 设置允许所有来源跨域
app.UseCors(options =>
{
options.AllowAnyHeader();
options.AllowAnyMethod();
options.AllowAnyOrigin();
options.AllowCredentials();
});
// 设置只允许特定来源可以跨域
app.UseCors(options =>
{
options.WithOrigins("http://localhost:3000", "http://127.0.0.1"); // 允许特定ip跨域
options.AllowAnyHeader();
options.AllowAnyMethod();
options.AllowCredentials();
});
3.在对应的控制器中加入跨域规则
引用 using Microsoft.AspNetCore.Cors;
[EnableCors("cors")]
如此完成部署;
测试方式与普通接口访问方式无异:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>跨域测试1</title>
<script src="~/Scripts/jquery-1.10.2.js"></script>
<script>
function btnGet() {
$.ajax({
url: 'https://localhost:44355/api/values',
type: "Get",
dataType: "json",
success: function (data) {
alert("成功");
},
error: function (data) {
alert("失败");
}
});
}
</script>
</head>
<body>
<div>
<input type="button" id="btn" value="测试跨域" onclick="btnGet()" />
</div>
</body>
</html>
参考页面:
https://www.cnblogs.com/dotnet261010/p/10177166.html