使用凭据

时间:2017-09-13 08:56:57

标签: angularjs asp.net-web-api asp.net-core cors

我正在使用web api core 1.1和angular 2。 我在每个HTTP请求中使用像令牌和https这样的凭据。在Internet Explorer中启动时一切正常,但是当使用chrome和firefox时,我收到错误信息并获取我的凭据和Http请求。有人能告诉我为什么我会收到错误吗?感谢

public void ConfigureServices(IServiceCollection services)
{
    ...
    services.AddCors(opt =>
    {
       opt.AddPolicy("MyCorsPolicy", builder =>
           builder.AllowAnyOrigin()
           .AllowAnyMethod()
           .AllowAnyHeader()
           .AllowCredentials());
    });
    services.AddMvc();
    ...
}


public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
   ...
   app.UseCors("MyCorsPolicy");
   app.UseMvc();
   ...
}

我的ng2代码:

import {Injectable, OnInit} from '@angular/core'
import {Headers, Http, Response} from '@angular/http';
import {Observable} from 'rxjs/Observable';


@Injectable()
export class MyApiCallService implements OnInit{

constructor(private http: Http) { }

ngOnInit() {
   this.fetchCredentials
       .subscribe(c => this.token = c
        ,error => { console.log(error) });
}
private fetchCredentials(): Observable<any> {

    var apiUrl = 'http://localhost:2762/api/someEndpoint';
    return this.http.get(apiUrl,{ withCredentials: true })
               .map(response => response.json())
               .catch(this.handleError);
    }

}

1 个答案:

答案 0 :(得分:0)

默认情况下,它会清除所有自定义标题。

您必须使用WithExposedHeaders("HeaderName")

例如:

        app.UseCors(options =>
    {
        options.AllowAnyHeader();
        options.WithExposedHeaders("X-Pagination");
        options.AllowAnyOrigin();
        options.AllowAnyMethod();
    });

因此,当您从客户端进行HTTP呼叫时,您将能够看到您的标题。