【发布时间】:2020-07-31 09:58:00
【问题描述】:
我正面临这个问题:
从源“http://localhost:4200”访问“http://localhost:5000/api/surpactemp/”处的 XMLHttpRequest 已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:预检请求不允许重定向。
在后端我尝试了这种方法但没有成功:
.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod()
我一直在尝试使用 Microsoft 参考(如下)解决问题的几种方法,但到目前为止都没有成功。 另外,我已经尝试过不在 Angular 上传递 headers 对象,然后,我收到错误:
请求中没有“Access-Control-Allow-Origin”标头
环境:
- Dotnet Core 3.1
- 角度 8
后端:Startup.cs
//ConfigureServices
services.AddCors(options =>
{
options.AddPolicy(name: "CorsPolicy",
builder => builder.WithOrigins("http://localhost:4200")
.WithHeaders(HeaderNames.ContentType, "application/json")
.WithMethods("PUT", "DELETE", "GET", "OPTIONS", "POST")
);
});
//Configure
app.UseHttpsRedirection();
app.UseRouting();
app.UseCors("CorsPolicy");
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
前端:form-service.ts
httpOptions = {
headers: new HttpHeaders({
// 'Content-Type': 'application/json',
// 'withCredentials': 'false',
// 'Access-Control-Allow-Origin': '*',
'Content-Type': 'application/json'
})
};
return this.httpClient.post('http://localhost:5000/api/surpactemp/', JSON.stringify(data.path), this.httpOptions);
参考:https://docs.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-3.1#preflight-requests
【问题讨论】:
-
UseCors的电话在哪里?它在中间件管道设置中的位置很重要。 -
@KirkLarkin 在后端部分,app.UseCors("CorsPolicy")
-
是的,我知道。我的意思是它在
Startup.Configure内的什么位置?之间还有哪些电话?中间件顺序很重要,因此可能您的顺序有误。
标签: c# angular asp.net-core .net-core asp.net-core-webapi