您好,我尝试从http
前端向get
发出.NET Core Console App
Angular 2
请求,但出现以下错误:
Access to XMLHttpRequest at 'http://127.0.0.1:9300/api/getusers' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
对我来说,这很奇怪,因为我已经在服务器端启用了CORS
,如您在下面的Startup
类中所见。
启动
public class Startup {
public Startup(IConfiguration configuration) {
Configuration = configuration;
}
public void ConfigureServices(IServiceCollection services) {
services.AddOptions();
services.AddMvc();
}
public IConfiguration Configuration;
public void Configure(IApplicationBuilder app) {
Console.WriteLine("request delievered");
Debug.WriteLine("Entered Server !");
app.UseMvc();
app.UseCors(x => { x.AllowAnyHeader(); x.AllowAnyOrigin();x.AllowAnyMethod(); });
}
}
我从UI
发出这样的请求:
@Injectable()
export class UserService{
private static baseUrl:string="http://127.0.0.1:9300/api";
constructor(private http:HttpClient) {
}
getClientsAsync():Promise<User[]>{
let route=UserService.baseUrl+"/getusers";
var data=(this.http.get(route) //should i have some headers here?
.map(resp=>resp)
.catch(err=>
Observable.throwError(err)
) as Observable<User[]>).toPromise<User[]>();
return data;
}
}
PS 我已经尝试使用Postman
并且请求有效,但是在angular 2
中,我的{{1}中没有包含任何headers
}方法。这可能是问题吗?
答案 0 :(得分:4)
您需要将UseCors
放在UseMvc
之前。
public void Configure(IApplicationBuilder app) {
Console.WriteLine("request delievered");
Debug.WriteLine("Entered Server !");
app.UseCors(x => { x.AllowAnyHeader(); x.AllowAnyOrigin();x.AllowAnyMethod(); });
app.UseMvc();
}
这是因为UseCors添加了中间件(UseMvc也是如此),并且中间件从上到下依次执行。因此,该请求永远不会到达CORS中间件。