EnableCorsAttribute不工作但似乎配置?

时间:2018-04-04 23:12:33

标签: angular cors asp.net-web-api2

我在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."

My 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 );
  }
}

知道我可能需要做些什么来回避这个错误?

2 个答案:

答案 0 :(得分:0)

如果要为所有控制器全局注册CORS,那么我建议将此块添加到Global.asax.cs文件中。当然可以根据您的需要进行修改。

   protected void Application_BeginRequest(object sender, EventArgs e)
   {
        HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "http://localhost:4200");
        if (HttpContext.Current.Request.HttpMethod != "OPTIONS") return;
        HttpContext.Current.Response.AddHeader("Cache-Control", "no-cache");
        HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST, PUT");
        HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept, Authorization ");
        HttpContext.Current.Response.End(); 
   }

答案 1 :(得分:0)

你得到这个错误,因为你没有为预检请求设置cors。我设置令牌时遇到了同样的问题,这就是我解决这个问题的方法: 1.在我安装的NuGet包中:"Microsoft.Owin.Cors" 2.在我的配置文件"APP_START/starup.cs"中,我添加了:

public void ConfigureAuth(IAppBuilder app)
        {
            //*enable cors*//
            app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
            app.UseOAuthBearerTokens(OAuthOptions);
    }

Here您可以找到有关thids问题的更多信息。