Web Api 2适用于邮递员,但不适用于Angular 2

Dav*_*dze 4 c# asp.net-web-api2 angular

邮递员要求: 在此处输入图片说明

邮递员一切都很好。我在服务器上发布了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);
  }
Run Code Online (Sandbox Code Playgroud)

它说错误:

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>
Run Code Online (Sandbox Code Playgroud)

我在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>
Run Code Online (Sandbox Code Playgroud)

有什么建议么?

Nor*_*csi 6

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

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

之后,根据OPTIONS响应的标头,浏览器会将IF允许的所有内容(如来源,方法等)发送GEThttp://foo.com/bar


Pie*_*run 2

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

您可以在这里看到原因,可能是由于 Content-Type 或任何其他标头(X-Requested-With ?)。

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