【问题标题】:Enable Cors .web api core 1.1 with credentials使用凭据启用 Cors .web api core 1.1
【发布时间】:2018-02-21 21:41:29
【问题描述】:

我正在使用 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);
    }

}

【问题讨论】:

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


    【解决方案1】:

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

    你必须使用WithExposedHeaders("HeaderName")

    例如:

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

    因此,当您从客户端进行 HTTP 调用时,您将能够看到您的标头。

    【讨论】:

      猜你喜欢
      • 2017-11-22
      • 2017-03-15
      • 2019-02-11
      • 2019-01-24
      • 2017-02-08
      • 2019-10-03
      • 2018-01-01
      • 2017-07-01
      • 1970-01-01
      相关资源
      最近更新 更多