【问题标题】:WebAPI MethodNotAllowed when CORS enabled启用 CORS 时的 WebAPI MethodNotAllowed
【发布时间】:2018-09-19 23:10:39
【问题描述】:

我正在使用 Angular 5 组件中的 WebAPI 2.0 Post 方法。 WebAPI 启用了 CORS(显示在 Chrome 的响应选项卡中),但在点击它时,显示为 MethodNotAllowed。不知道这里有什么问题。身份验证使用不记名令牌。邮递员命中是正确的。但是通过角度时无法访问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”,web api 会报告 cors 失败,如果我在 oauth 之后添加它,它会在 OAuth 上报告 cors 错误...不确定在哪里设置!!!

【问题讨论】:

  • 试试 Fiddler,它会给你确切的错误。我认为,参数与 API 方法的预期不同。
  • 你也可以显示 WebAPI 代码吗?
  • 你确定它是 POST api 方法吗?它可能是 GET。检查您的 API 一次。
  • @DheerajKumar 添加了 webapi 代码。
  • 为有效载荷移除 JSON.stringify

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


【解决方案1】:

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

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

OPTIONS 在每个 post 和 put 请求之前发送,默认禁用。

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

    • 没有区别。导致“net::ERR_CONNECTION_RESET”
    【解决方案3】:

    最终,这篇文章帮助了我owin cors or web api cors

    以下内容无需更新:-

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

    最终改动

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

    感谢大家的支持和帮助

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-07-18
      • 2015-10-07
      • 2019-07-16
      • 2021-04-09
      • 1970-01-01
      • 2013-07-04
      • 2021-12-30
      • 2017-02-22
      相关资源
      最近更新 更多