api是AspNetCore WebApi,具有Windows身份验证和启用CORS的默认配置。客户端是Angular,具有GET和POST方法。
GET呼叫成功:
this.http.get("https://localhost:44358/api/values", {withCredentials:true})
.subscribe(a=> {
console.log(a);
this.list=a;
});
POST失败:
this.http.post("https://localhost:44358/api/values", {value:"aaa"}, {withCredentials:true})
.subscribe(a=> {
console.log(a);
this.list=a;
});
02例外
OPTIONS https://localhost:44358/api/values 401 (Unauthorized)
和
Access to XMLHttpRequest at 'https://localhost:44358/api/values' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
有什么好主意吗?
POST使浏览器在真正的POST之前将OPTIONS发送到web api。但是,webapi拒绝此调用,因为配置仅基于Windows身份验证。解决方案是为控制器启用Windows身份验证以及对launchSetting.json
中的OPTIONS进行匿名身份验证。
"iisSettings": {
"windowsAuthentication": true,
"anonymousAuthentication": true,
并在AddMvc
的Startup.cs
之前加1行
services.AddAuthentication(IISDefaults.AuthenticationScheme);
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);