【问题标题】:Access to XMLHttpRequest at In Asp.net core 2.2.1在 Asp.net core 2.2.1 中访问 XMLHttpRequest
【发布时间】:2019-06-17 23:32:25
【问题描述】:

在我的 Asp.net 核心项目中,我使用 Microsoft.AspNetCore.App Version="2.2.1" 并在启动服务中调用 AddCors
Startup.cs :

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

    .....

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            app.UseCors(policyName: "CorsPolicy");  

            .... 

Controller

 [Route("api/[controller]")]
    [EnableCors("CorsPolicy")]
    public class ManageUsersController : Controller
    { ...

在 angular 5 App 中调用 Web API 时在浏览器的控制台中显示此错误

访问 XMLHttpRequest 在 'http://localhost:5000/api/Account/LoginByPortal' 来自原点 “http://localhost:4200”已被 CORS 策略阻止:响应 预检请求未通过访问控制检查: 响应中的“Access-Control-Allow-Origin”标头不能是 当请求的凭据模式为“包含”时,通配符“*”。这 XMLHttpRequest 发起的请求的凭证模式是 由 withCredentials 属性控制。

角度服务:

loginByPortal(credentials: Credentials): Observable<userLoginViewmodel> {
    const headers = new HttpHeaders({ 'Content-Type': 'application/json' });
    return this.http
      .post(`${this.appConfig.apiEndpoint}/Account/LoginByPortal`, credentials,
       { headers: headers, withCredentials: true /* For CORS */ })     
      .map(response => response || {})
      .catch((error: HttpErrorResponse) => Observable.throw(error));
  }

我不想使用.WithOrigins("http://localhost:4200"
我想在 CoresPloicy 中使用 AllowAnyOrigin
有什么问题?如何解决?

【问题讨论】:

  • 要么删除AllowCredentials,要么指定一个来源。
  • @Sasan 删除 AllowCredentials 但再次显示错误
  • 那个withCredentials: true 怎么样?
  • 能否提供asp.net核心日志

标签: angular asp.net-core


【解决方案1】:

这里是解决方案:https://stackoverflow.com/a/53790841/8801075

app.UseCors(builder => builder
                .AllowAnyHeader()
                .AllowAnyMethod()
                .SetIsOriginAllowed((host) => true)
                .AllowCredentials()
            );

【讨论】:

    猜你喜欢
    • 2020-03-01
    • 2021-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多