启用CORS时,We​​bAPI MethodNotAllowed

时间:2018-04-10 10:53:32

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

我正在使用Angular 5组件中的WebAPI 2.0 Post方法。 WebAPI启用了CORS(在Chrome的“响应”选项卡中显示),但在点击它时,显示为MethodNotAllowed。不知道这里有什么不对。身份验证使用承载令牌。邮差命中是正确的。然而,当通过角度

时无法击中api
Account_logo.sendKeys("C:\\Users\\romit\\Desktop\\LOGO.jpg");

WebAPI代码

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

enter image description here

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

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

如果我首先使用“UseCors”调用,那么web api会报告cors失败,如果我将其添加到oauth之后,它会报告OAuth上的cors错误...不知道在哪里设置它!

3 个答案:

答案 0 :(得分:0)

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

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

答案 1 :(得分:0)

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

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

OPTIONS在每个帖子和发出请求之前发送,默认情况下已禁用。

答案 2 :(得分:0)

最后,这篇文章帮助了我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();
    }

感谢大家的支持和帮助

相关问题