且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Angular 2调用ASP.NET WebAPI

更新时间:2023-02-15 20:18:33

我也遇到了这个问题.我的Angular2-rc4应用在另一个域上调用了.NET Core 1.0.0 WebAPI应用.

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

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

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

  public void ConfigureServices(IServiceCollection服务){var corsBuilder = new CorsPolicyBuilder();corsBuilder.AllowAnyHeader();corsBuilder.AllowAnyMethod();corsBuilder.AllowAnyOrigin();corsBuilder.AllowCredentials();services.AddCors(options =>{options.AddPolicy("AllowAll",corsBuilder.Build());});}公共无效的Configure(IApplicationBuilder应用程序,IHostingEnvironment env,ILoggerFactory loggerFactory){app.UseCors("AllowAll");} 

当然,可以根据应用程序的需要设置策略,这仅允许所有测试.示例此处提供更多详细信息.

I am trying to call a WebAPI using Angular but running into a credential not authorized issue. It works fine in IE but in Chrome and FF (401 unauthorized), the credentials are not forwarded.

I think the solution is to add the default credential into the call in Angular, but I am not sure how to do it or maybe there is some other solution.

Angular calls

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

    }

}

I was having this issue as well. My Angular2-rc4 app calls a .NET Core 1.0.0 WebAPI app on another domain.. posting this in case it may help others.

As mentioned by others, in Angular2 pass withCredentials true:

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

In your WebAPI project you can set CORS policies in Startup.cs (instead of web.config):

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

Of course, set your policies based on your app's needs, this just allows all for testing. Example here and official .NET Core docs here provide more details.