【发布时间】:2020-09-02 14:31:34
【问题描述】:
我们有 asp.net core web api 和 angular 9 应用程序。 Asp.net 核心 Web API 使用以下代码启用了 Windows 身份验证。另外,为了测试,我为所有人启用了 CORS。
"iisSettings": {
"windowsAuthentication": true,
"anonymousAuthentication": false,
"iisExpress": {
"applicationUrl": "http://localhost:44305",
"sslPort": 0
}
},
services.AddCors(options =>
{
options.AddPolicy("CustomCorsPolicy",
builder => builder.WithOrigins("http://localhost:4200")
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials());
});
app.UseCors("CustomCorsPolicy");
当我发出 GET 请求时,我得到了响应,但发出 POST 请求时却失败了。我已经将 withCrendtial 设置为 true。下面是我设置的拦截器
intercept(httpreq: HttpRequest<any>, next: HttpHandler):
Observable<HttpEvent<any>> {
httpreq= httpreq.clone({
withCredentials: true
});
return next.handle(httpreq);
}
另外,像这样在应用模块上注册拦截器
{
provide: HTTP_INTERCEPTORS,
useClass: WdAuthHttpInterceptor,
multi: true
},
从源“http://localhost:4200”访问“https://localhost:44305/anotherdata/test”处的 XMLHttpRequest 已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。
【问题讨论】:
-
您提供的代码看起来不错。您是否在提供程序的模块中连接了拦截器,例如在 app.module.ts 中。类似 import {HttpClientModule, HTTP_INTERCEPTORS} from '@angular/common/http';和提供者: [ // Http Interceptor(s) - 添加客户端凭据 [ { 提供:HTTP_INTERCEPTORS, useClass: HttpRequestInterceptor, multi: true } ], ],
-
是的,我已经在app模块上注册了。
-
一个想法。如果很明显,请道歉 - 您的拦截器在 localhost:4200 或 localhost:8000 中。它需要在localhost:4200 中,不过我相信你已经这样做了。
-
locahost:8000 是 API,localhost:4200 是 Angular 应用程序。我在本地主机上有拦截器:4200