Angular 2调用ASP.NET WebAPI [英] Angular 2 calling ASP.NET WebAPI

查看:49
本文介绍了Angular 2调用ASP.NET WebAPI的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Angular调用WebAPI,但是遇到证书未授权的问题.它在IE中可以正常工作,但在Chrome和FF(未经授权的401)中,不会转发凭据.

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

角度通话

 从'angular2/http'导入{Http};从"angular2/core"导入{Injectable};导入'rxjs/Rx';@Injectable()导出类MyListService {构造函数(私有_http:Http){}getMyList(){//返回一个可观察的返回this._http.get('http:////localhost:2311/api/MyListApi').map((response)=> {返回response.json();});//.retry(3);}} 

解决方案

我也遇到了这个问题.我的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 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.

这篇关于Angular 2调用ASP.NET WebAPI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆