【发布时间】:2020-11-24 15:26:50
【问题描述】:
我无法从我的 http 请求中获取数据。在服务器端,我有以下内容
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddSwaggerGen();
services.AddScoped<IRepository, Repository>();
services.AddAuthentication(IISDefaults.AuthenticationScheme);
services.AddCors(options =>
options.AddDefaultPolicy(builder => builder
.WithOrigins("http://localhost:4200")
.AllowAnyMethod().AllowAnyHeader().AllowCredentials()));
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "KYCDB API");
});
app.UseHttpsRedirection();
app.UseRouting();
app.UseCors();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
该项目还开启了 Windows 身份验证,关闭了匿名。
"iisSettings": {
"windowsAuthentication": true,
"anonymousAuthentication": false,
"iisExpress": {
"applicationUrl": "http://localhost:51721",
"sslPort": 49321
}
}
在角度方面我得到了一个组件
export class HeaderComponent implements OnInit {
currentEmployee$: Observable<Employee>;
constructor(private userService: UserService) { }
ngOnInit(): void {
this.currentEmployee$ = this.userService.getCurrentEmployee();
}
}
还有一个拦截器
@Injectable()
export class ApiInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
req = req.clone({ withCredentials: true });
return next.handle(req);
}
}
当页面加载时,我收到 2 个警告和一个错误
警告:跨域请求被阻止:同源策略不允许读取位于 http://localhost:51721/employee/current 的远程资源。 (原因:CORS 标头“Access-Control-Allow-Origin”缺失)。
警告:跨域请求被阻止:同源策略不允许读取位于 http://localhost:51721/employee/current 的远程资源。 (原因:CORS 请求未成功)。
错误:http://localhost:51721/employee/current 的 Http 失败响应:0 未知错误
我需要纠正什么?
【问题讨论】:
-
如果我注释掉 app.UseHttpsRedirection(); 一切都会顺利进行
-
我发现您的网址有些不匹配。您使用
.WithOrigins("http://localhost:4200")定义 CORS,使用http://localhost:51721启动,并可能重定向到另一个启用 HTTPS 的 URL。尝试在WithOrigins调用中设置所有有效来源。 -
WithOrigins 不是我放置所有客户端 url 的地方吗?这就是为什么我把 Angular 放在那里。我也在 environment.ts 文件中的 Angular 项目中使用的启动 url。
-
是的,如果您的客户端 Angular 应用程序托管在
http://localhost:4200上,那么它是正确的。起初我以为你也从 ASP.NET 应用程序为客户端提供服务。 -
如果我删除 https 重定向,我无法理解为什么一切正常。招摇也不能在 https 上工作。
标签: angular cors httprequest asp.net-core-webapi