【问题标题】:Web Api 2 works with postman but fails with Angular 2Web Api 2 与邮递员一起工作,但与 Angular 2 一起失败
【发布时间】:2017-07-17 21:17:50
【问题描述】:

邮递员要求:

邮递员的一切都很好。我在服务器上发布了 Bearer 令牌并得到了预期的结果。

Angular 2 请求:

    //app component
    test(){
        return this.httpService.get('api/user/get', 'application/json')
          .subscribe(data=>{
              console.log({'loggedIn': true, 'messageText': 'test succeeded'});
            },
            error=>{
              console.log({'loggedIn': false, 'messageText': error});
            }
          );
      }

//http-service
get(url:string, contentType:string):Observable<any> {
    let baseUrl:string = "http://localhost:1382/";

    let headers = new Headers({
      'Accept': 'application/json'
    });

    //append content-type to headers
    headers.append('Content-type', contentType);

    //check if localStorage contains token. If yes, append authorization to headers
    let token = localStorage.getItem('access_token');
    if (token !== '[object Object]' && token !== null) {
      headers.append('Authorization', 'Bearer' + ' ' + token);
    }

    let requestOptions = new RequestOptions({headers: headers});

    //send get request
    return this.http.get(baseUrl + url, requestOptions)
      .map((res:Response)=>res.json())
      .catch(this.handleError);
  }

它说错误:

OPTIONS http://localhost:1382/api/user/get 405 (Method Not Allowed)

XMLHttpRequest cannot load http://localhost:1382/api/user/get. Response for preflight has invalid HTTP status code 405

<Error>
<Message>Authorization has been denied for this request.</Message>
</Error>

我在 Web Api 2 web.config 中启用了 CORS,如下所示:

<system.webServer>
<httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*" />
        <add name="Access-Control-Allow-Headers" value="Content-Type, Authorization, Accept" />
        <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
      </customHeaders>
    </httpProtocol>
  </system.webServer>

有什么建议吗?

【问题讨论】:

  • 似乎有点明显,但是您是否调试/检查过它实际上是否在命中该代码(即正在附加令牌)并且令牌实际上是有效的? if (token !== '[object O... 声明在我看来有点可疑。您还可以检查提琴手的流量。有时您并没有发送您认为发送的内容! :)... 有时格式错误的请求可能会出现您所看到的错误。
  • 如果您尝试临时硬编码所有请求信息(URL、标头等),以确保它不是您的 get() 方法中的逻辑那是错的吗?换句话说,就像在 Postman 中一样,将所有数据作为字符串输入。
  • 您能否查看实际的网络请求并验证您是否像使用邮递员一样添加了所有标头?
  • WebApiConfig.csGlobal.asax 添加app.UseCors()。可能需要 nuget Microsoft.AspNet.WebApi.Cors

标签: c# angular asp.net-web-api2


【解决方案1】:

它在邮递员中工作,因为这是一个扩展,它只是发送请求。
另一方面,从浏览器发送请求时,出于安全原因,请求的发送方式不同。
首先,浏览器向http://foo.com/bar 发送一个OPTIONS 请求(所谓的预检请求)。这是为了确定是否可以接受带有这些参数的请求。
您的后端应处理请求、响应并设置响应标头,例如:

  • Access-Control-Allow-Origin
  • Access-Control-Allow-Headers
  • Access-Control-Allow-Credentials
  • Access-Control-Allow-Methods

之后,根据OPTIONS 响应的标头,如果来源、方法等一切都允许,浏览器会将GET 发送到http://foo.com/bar

【讨论】:

    【解决方案2】:

    您实际上确实有一个预检请求(以 405 失败)。

    您可以看到here 为什么,可能是由于 Content-Type 或任何其他标头(X-Requested-With ?)。

    如果你想保留这个预检,你必须在 webapi 中处理它并禁用授权或至少返回 200(你可以看看here

    【讨论】:

      【解决方案3】:

      感谢大家的回答和建议。我总结了所有这些信息,此外我还找到了这个答案:https://stackoverflow.com/a/39397016/4559099GrantResourceOwnerCredentials 我添加了context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "http://localhost:4200" });

      我在WebApiConfig 中添加了config.EnableCors(new EnableCorsAttribute("http://localhost:4200, ", "*", "*"));,一切正常。

      其实我不明白为什么评论的作者写了config.EnableCors(new EnableCorsAttribute("http://localhost:4200, ", "*", "*")); 而不是config.EnableCors(new EnableCorsAttribute("http://localhost:4200", "*", "*")); 但它工作正常。如果有人解释这一点,那将非常有帮助。

      【讨论】:

        猜你喜欢
        • 2019-02-10
        • 1970-01-01
        • 1970-01-01
        • 2016-10-23
        • 1970-01-01
        • 2021-05-17
        • 1970-01-01
        • 1970-01-01
        • 2015-01-01
        相关资源
        最近更新 更多