【发布时间】:2019-05-16 23:02:59
【问题描述】:
我有一个 C# WebApi 服务器,在这个项目中,我在我的 WebAPiConfig.cs 中启用了 cors
var cors = new EnableCorsAttribute(
origins: "*",
headers: "*",
methods: "*" );
cors.SupportsCredentials = true;
config.EnableCors(cors);
在我的 Angular 服务中,我这样设置 HTTP 标头
getRouteGeneralTable(routeType: string, pattern: string): Observable<DBrow[]> {
const httpHeader = new HttpHeaders({
'Content-Type': 'application/json',
'withCredentials': 'true',
'Access-Control-Allow-Origin':'*',
'Accept': 'application/json',
'Access-Control-Allow-Credentials': 'true',
'Access-Control-Allow-Methods': 'POST, GET, OPTIONS, PUT'
});
return this.http.get<DBrow[]>(this.baseURL + 'getgeneralroutedata/' + routeType + '/' + pattern, {headers: httpHeader} )
.pipe(
retry(3),
catchError(this.handleError)
);
}
我在尝试执行获取请求时遇到这些错误:
Access to XMLHttpRequest at SOMEADDRESS 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.
请问我该如何解决?
【问题讨论】:
-
@SaddamPojee 我试过了,我不想使用代理,因为它没有安全性。
-
尝试从您的请求中删除整个“{headers: httpHeader}”,看看会发生什么。设置 httpHeader 值的代码在多个方面是错误的:(1) 'withCredentials' 不是标头名称,(2) 所有 Access-Control-Allow-* 标头都是响应标头,而不是请求标头,(3)为 GET 请求设置 Content-Type 标头是没有意义的——因为 GET 请求没有请求正文。
-
@sideshowbarker 删除了它,第一个获取请求有效!但是我的第二个获取请求不起作用。我还从中删除了头文件,但在请求的资源上没有出现“Access-Control-Allow-Origin”头文件。
标签: c# angular asp.net-web-api cors