【问题标题】:Angular 2 calling ASP.NET WebAPIAngular 2 调用 ASP.NET WebAPI
【发布时间】:2016-09-06 02:56:36
【问题描述】:

我正在尝试使用 Angular 调用 WebAPI,但遇到了凭据未授权的问题。它在 IE 中运行良好,但在 Chrome 和 FF(401 未经授权)中,凭据不会被转发。

我认为解决方案是将默认凭据添加到 Angular 中的调用中,但我不知道该怎么做,或者可能还有其他解决方案。

角度调用

import {Http} from 'angular2/http';
import {Injectable} from 'angular2/core';
import 'rxjs/Rx';

@Injectable()
export class MyListService{

    constructor(private _http: Http) { }

    getMyList() {
    //return an observable
    return this._http.get('http:////localhost:2311/api/MyListApi')

        .map((response) => {
            return response.json();
        });
        //.retry(3);

    }

}

【问题讨论】:

    标签: javascript c# asp.net angularjs asp.net-web-api


    【解决方案1】:

    你可以试试这个方法:

    return this._http.get('http:////localhost:2311/api/MyListApi', {
            credentials: RequestCredentialsOpts.Include
        }).map((response) => {
                return response.json();
            });
        }
    

    看起来像最近的fix Angular2。也可以查看this的答案。

    【讨论】:

    • RequestOptionsArgs 中好像只能指定 url、method、search、headers 和 body。我在我的环境中运行 angular2 2.0.0-beta.17。我不可能是唯一一个遇到这个问题的人吗?
    • mmm 你检查过这个吗:stackoverflow.com/questions/32905399/… 或许可以给你一些帮助。
    • 最近打了补丁,所以你可以在通话中使用 withCredentials,true。如果在不同的服务器/端口上运行,请注意 CORS 需求
    【解决方案2】:

    我也遇到了这个问题。我的 Angular2-rc4 应用程序调用另一个域上的 .NET Core 1.0.0 WebAPI 应用程序。发布此内容以防它可能对其他人有所帮助。

    正如其他人所提到的,在 Angular2 中传递 withCredentials true:

    getUser() {
        return this.http.get(this._apiUrl + "/account/GetUser", { withCredentials: true })
            .toPromise()
            .then(response => response.json().data)
            .catch(this.handleError);
    }
    

    在您的 WebAPI 项目中,您可以在 Startup.cs(而不是 web.config)中设置 CORS 策略:

    public void ConfigureServices(IServiceCollection services)
    {
        var corsBuilder = new CorsPolicyBuilder();
        corsBuilder.AllowAnyHeader();
        corsBuilder.AllowAnyMethod();
        corsBuilder.AllowAnyOrigin();
        corsBuilder.AllowCredentials();
        services.AddCors(options =>
        {
            options.AddPolicy("AllowAll", corsBuilder.Build());
        });
    }
    
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        app.UseCors("AllowAll");
    }
    

    当然,根据您的应用需求设置您的政策,这只是允许所有测试。示例 here 和官方 .NET Core 文档 here 提供了更多详细信息。

    【讨论】:

      猜你喜欢
      • 2016-03-18
      • 2020-01-27
      • 2023-02-20
      • 2017-08-05
      • 1970-01-01
      • 1970-01-01
      • 2012-06-20
      • 1970-01-01
      • 2018-07-08
      相关资源
      最近更新 更多