【问题标题】:EnableCorsAttribute not working but seems to be configured?EnableCorsAttribute 不起作用,但似乎已配置?
【发布时间】: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


    【解决方案1】:

    您收到此错误是因为您没有为预检请求设置 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你可以找到更多关于这个问题的信息。

    【讨论】:

      【解决方案2】:

      如果您想为所有控制器全局注册 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(); 
         }
      

      【讨论】:

        猜你喜欢
        • 2018-06-07
        • 1970-01-01
        • 2023-04-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-12-20
        • 1970-01-01
        相关资源
        最近更新 更多