【发布时间】:2018-09-14 15:39:38
【问题描述】:
我在 WebApiConfig.cs 文件中的 Web API 2 应用中启用了 CORS,如下所示:
// enable cors
var cors = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(cors);
但是,我的 Angular 5 应用程序仍然收到以下错误:
"Failed to load http://localhost:52056/api/v1/users/search/: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access. The response had HTTP status code 401."
我的 Angular 服务非常基础:
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import { User } from './user.ts';
const httpOptions = {
headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};
@Injectable()
export class UserService {
constructor(private http:HttpClient) { }
public search(userSearchRequest) : User[]{
var userSearchUrl = "http://localhost:52056/api/v1/users/search/";
return this.http.post<UserSearchRequest>(userSearchUrl, userSearchRequest, httpOptions );
}
}
知道我可能需要做什么才能避开这个错误吗?
【问题讨论】:
标签: c# angular cors asp.net-web-api2