angular - 在预检期间发布未能阻止 CORS 策略,即使我已将其添加到拦截器中,也不会显示“Access-Control-Allow-Origin”标头
问题描述
使用:Angular 7、.net core、web api
我最近更改了我的应用程序以使用 Windows 身份验证,现在我曾经工作的请求对于任何发布和放置(获取工作)都失败了。我得到一个
Access to XMLHttpRequest at 'https://localhost:44372/api/tasks' 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.
我必须添加一个角度拦截器才能让 get 请求在启用 Windows 身份验证的情况下工作。
@Injectable()
export class CredentialsInterceptor implements HttpInterceptor {
intercept(request: HttpRequest<any>, next: HttpHandler):
Observable<HttpEvent<any>> {
request = request.clone({
withCredentials: true
});
return next.handle(request);
}
}
我的 startup.cs 正在像这样添加 CORS(我必须 setIsOriginAllowed 才能使 get 请求工作)
services.AddCors(o => o.AddPolicy("AllowAll", builder =>
{
builder.SetIsOriginAllowed((host) => true)
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials();
}));
...//Configure
app.UseCors("AllowAll");
app.UseMvc(routes =>
{
...
我也尝试过指定来源或方法 .WithOrigins(" https://localhost:4200 ", " http://localhost:4200 ") 或 .AllowAnyOrigin()
以及在拦截器中手动添加标题
intercept(request: HttpRequest<any>, next: HttpHandler):
Observable<HttpEvent<any>> {
request = request.clone({
withCredentials: true
});
request.headers.append('Access-Control-Allow-Origin', 'http://localhost:4200');
return next.handle(request);
我错过了什么?我已经在谷歌上搜索了几个小时。我了解如果未指定允许的来源,CORS 将被阻止。其他 StackOverflows 说它不能是客户端,但我觉得客户端请求没有发送“Access-Control-Allow-Origin”标头。如何测试以确保设置了标头?为什么 Get 工作而不是 Put 请求?
解决方案
所有其他帖子都说明了问题是什么,但没有说明问题的解决方案是什么。OPTIONS 请求是在没有授权标头的情况下放置的。我能够发出 GET 请求,因为 Windows 身份验证标头被传递,但是当我发出 PUT 请求时,必须首先发送一个不包含标头的 OPTIONS。
为了让服务器允许选项,我必须允许选项的匿名身份验证。我通过在项目属性-> 调试部分中选择它来做到这一点。
推荐阅读
- post - 我想从应用程序捕获 HTTPS 流量,但它不起作用
- android - Android - onCreate 中的完成()行为不一致
- r - 如何在R中找到散点图的细胞倍增时间?
- php - Laravel 多对多关系在一个模型上失败,但在另一个模型上失败
- api - 检测vue组件完成渲染
- ocr - OCR 将 E 检测为 £
- amazon-web-services - ssh ec2 密钥错误权限被拒绝(公钥)
- odata - 如何将 Odata 请求转换为 JSON 响应
- java - 从一个 java 文件中的一个 ArrayList 中提取数据,并将其显示在 ArrayList 中的不同 java 文件中
- laravel - Facade\Ignition\Exceptions\ViewException count():参数必须是数组或者实现了Countable的对象(View: