我有一个C#WebApi服务器,并且在此项目中,我在WebAPiConfig.cs中启用了cors
var cors = new EnableCorsAttribute(
origins: "*",
headers: "*",
methods: "*" );
cors.SupportsCredentials = true;
config.EnableCors(cors);
在我的角度服务中,我像这样设置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)
);
}
我在尝试执行get请求时遇到这些错误:
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.
请问如何解决?
答案 0 :(得分:0)
将以下内容添加到您的Web.Config文件中:
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Content-Type" />
<add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
<add name="Access-Control-Allow-Credentials" value="true" />
</customHeaders>
</httpProtocol>
</system.webServer>