服务器使用Cors,但UI仍会出现允许来源错误

时间:2018-11-13 08:18:28

标签: asp.net-core cors

您好,我尝试从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 }方法。这可能是问题吗?

1 个答案:

答案 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中间件。