启用 CORS 时 WebAPI MethodNotAllowed

WebAPI MethodNotAllowed when CORS enabled

我正在使用 Angular 5 组件中的 WebAPI 2.0 Post 方法。 WebAPI 启用了 CORS(显示在 Chrome 的响应选项卡中),但在点击它时,显示为 MethodNotAllowed。不知道这里出了什么问题。身份验证使用不记名令牌。 Post人打就对了。然而在通过 angular

时无法命中 api
  private PopulateHeaders() {
    this.userIdAuthToken = localStorage.getItem(this.authToken);

    let headers = new HttpHeaders({
      'Content-Type': 'application/json'
    });

    //   Once security is implemented, add the token here 
    if (this.userIdAuthToken)
      headers.append('Authorization', 'Bearer ' + this.userIdAuthToken);

    this.httpOptions = {
      headers: headers
    };
  }

  postProject(name: string, details: string): Observable<HttpEvent<Project>> {
    var data = { name: name, details: details };

    this.PopulateHeaders();

    let saveRequest = this._http.post<Project>(
      this.apiUrl + '/project' + '/post',
      JSON.stringify(data),
      this.httpOptions);

    return saveRequest;
  }

WebAPI 代码

    [Authorize(Users = "admin@myapp.com")]
    public int Post([FromBody]Project project)
    {
        lock (this)
        {
            project.Id = projects.Count() + 1;
            projects.Add(project);
            return project.Id;
        }
    }

(仅供参考) 我在这里使用 OWIN 身份验证,我的启动文件如下:-

        public void Configuration(IAppBuilder app)
        {
            // CORS has to be set first in order for it to be enabled for OWIN

            app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);

            this.ConfigureOAuthTokenGeneration(app);

            this.ConfigureOAuthTokenConsumption(app);

            this.ConfigureWebApi();

            app.UseWebApi(HttpConfiguration);
}

如果我首先调用 "UseCors",网络 api 报告 cors 失败,如果我在 oauth 之后添加它,它会报告 OAuth 上的 cors 错误...不知道去哪里设置 !!!

在Global.asax.cs文件中添加以下代码

protected void Application_BeginRequest()
{
    if (Request.Headers.AllKeys.Contains("Origin") && Request.HttpMethod == "OPTIONS")
    {
        Response.Flush();
    }
}

您必须在服务器端启用 OPTIONS http 方法。将此添加到 Web.config 中的 <handlers></handlers> 字段:

<!-- Enable OPTIONS http request-->
<remove name="OPTIONSVerbHandler" />
<add name="OPTIONSVerbHandler" path="*" verb="OPTIONS" modules="ProtocolSupportModule" resourceType="Unspecified" requireAccess="Script" />

OPTIONS在每个post和put请求前发送,默认关闭

最终,这个 post 帮助了我 owin cors or web api cors

无需更新以下内容:-

  • app.UseCors(因为 CustomOAuthProvider 已经为所有人设置了 Cors)
  • WebAPI 需要使用 Cors,因此最好的注入方式是通过 WebAPI.Cors Nuget 和 EnableCors 方法..
  • OPTIONS 或 header 的 web.config 没有变化 (access-control-*)

最终更改

(WebAPI.Config) * 适用于所有人

var cors = new System.Web.Http.Cors.EnableCorsAttribute("*", "*", "*"); 
config.EnableCors(cors);

启动

  public void Configuration(IAppBuilder app)
    {
        // **No longer required**
        // app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);

        this.ConfigureOAuthTokenGeneration(app);

        this.ConfigureOAuthTokenConsumption(app);

        this.ConfigureWebApi();

        app.UseWebApi(HttpConfiguration);

        // No further configuration is now allowed. 
        HttpConfiguration.EnsureInitialized();
    }

感谢大家的支持和帮助