CORS无法用于从Ajax到ASP.NET Core Web API的调用

问题描述

它将在Ajax调用上引发此错误。 我还使用命名策略在Startup.cs中尝试了这些行。我在网上找到的所有方法均无效。 我确定我在某个地方犯了一些愚蠢的错误,但我没有看到它。

builder.WithOrigins("https://localhost:44380")
builder.WithOrigins("localhost:44380")
builder.WithOrigins("localhost")
[EnableCors("MyPolicy")] //in Controller.cs

Chrome浏览器控制台出现错误

enter image description here

Controller.cs

[Route("api/itexit")]
[EnableCors]
[ApiController]
public class ITExitController : ControllerBase
{
    //code...
}

Startup.cs

public void ConfigureServices(IServiceCollection services)
{
    services.AddControllers();
    services.AddSwaggerGen();

    services.AddCors();

    string connectionString = Configuration.GetConnectionString("DefaultConnection");
    services.AddDbContext<CoCFormsContext>(options => options.UsesqlServer(connectionString));
}
public void Configure(IApplicationBuilder app,IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }

    app.UseSwagger();
    app.UseSwaggerUI(c =>
    {
        c.SwaggerEndpoint("/swagger/v1/swagger.json","CoCForms.API");
    });

    app.UseHttpsRedirection();

    app.UseRouting();
    app.UseCors(builder =>
    {
        builder
        .AllowAnyOrigin()
        .AllowAnyMethod()
        .AllowAnyHeader();
    });
    app.UseAuthorization();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
    });
}

.cshtml页面中的Ajax调用

$.ajax({
    url: url,type: "GET",crossDomain: true,dataType: 'json',//dataType: 'jsonp',success: function (data,textstatus,jqXHR) {
//process data
    },error: function (jqXHR,exception) {
//process exception
    }
});

解决方法

尝试像这样使用命名策略:

 services.AddCors(o => o.AddPolicy("MyPolicy",builder =>
            {
                builder.AllowAnyOrigin()
                       .AllowAnyMethod()
                       .AllowAnyHeader();
            }));

还有这个

 app.UseCors("MyPolicy");

在这种情况下,您不需要控制器中的[EnableCors]。仅在使用AddDefaultPolicy时才需要它。...

,

真正的问题是该API需要Windows身份验证。错误确实是

401.2未经授权

(未在Chrome控制台中显示)。我通过从另一个C#项目而不是从Ajax调用中调用api来发现“未经授权”错误。

进行以下更改后,现在可以使用。

将这些额外的行添加到Ajax调用中:

crossDomain: true,xhrFields: {
    withCredentials: true
},

更新的Ajax呼叫:

$.ajax({
    url: url,type: "GET",crossDomain: true,dataType: 'json',xhrFields: {
        withCredentials: true
    },success: function (data,textstatus,jqXHR) {
        //process data
    },error: function (jqXHR,exception) {
        //process exception
    }
});

在Startup.cs中添加了这一行 将AllowAnyOrigin()替换为

builder.SetIsOriginAllowed(_ => true)

并添加了这一行

services.AddAuthentication(IISDefaults.AuthenticationScheme);

更新后的Startup.cs

public void ConfigureServices(IServiceCollection services)
{
    services.AddControllers();
    services.AddAuthentication(IISDefaults.AuthenticationScheme);
    services.AddSwaggerGen();

    services.AddCors(o => o.AddPolicy("MyPolicy",builder =>
    {
        builder.SetIsOriginAllowed(_ => true)
               .AllowAnyMethod()
               .AllowAnyHeader()
               .AllowCredentials();
    }));

    string connectionString = Configuration.GetConnectionString("DefaultConnection");
    services.AddDbContext<CoCFormsContext>(options => options.UseSqlServer(connectionString));
}

public void Configure(IApplicationBuilder app,IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }

    app.UseSwagger();
    app.UseSwaggerUI(c =>
    {
        c.SwaggerEndpoint("/swagger/v1/swagger.json","CoCForms.API");
    });

    app.UseHttpsRedirection();

    app.UseRouting();
    app.UseCors("MyPolicy");
    app.UseAuthorization();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
    });
}

向控制器添加了[Authorize]属性

[Route("api/itexit")]
[ApiController]
[Authorize]