asp.net core 2.0 api ajax跨域问题
API配置:
services.AddCors(options => { options.AddPolicy("any", builder => { builder.WithOrigins("http://localhost") //指定允许来源的主机访问 .AllowAnyMethod() .AllowAnyHeader() .AllowCredentials();//指定处理cookie }); }); //设置全局筛选器,全局控制器启用core services.Configure<MvcOptions>(options => options.Filters.Add(new CorsAuthorizationFilterFactory("any")));
客户端:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<meta charset="utf-8" />
<script src="jquery.min.js"></script>
</head>
<body>
<input id="login" value="登录" type="button" />
<input id="sava" value="保存" type="button" />
<span id="message"></span>
<script>
$("#sava").click(function () {
$.ajax({
type: 'GET',
url: "http://localhost:54821/api/v1/garbage/type",
data: { },
dataType: "json",
//必须有这项的配置,不然cookie无法发送至服务端
xhrFields: {
withCredentials: true
},
success: function (result) {
alert(result.code);
$("#message").html(result);
},
error: function (xhr,status) {
alert("失败");
$("#message").html(status);
}
});
})
</script>
</body>
</html>
此时设置全局启用,控制器中可以使用

浙公网安备 33010602011771号