ASP.NET Core 6 中的 'Access-Control-Allow-Origin'

12

已在Postman中进行了测试,工作正常。在浏览器中出现以下错误:

由于 CORS 策略,从源站'https://localhost:44426'到'http://localhost:5081/api/Accounting/GetSales'的 XMLHttpRequest 访问已被阻止:请求的资源上没有 'Access-Control-Allow-Origin' 标头。

这是一个带有 Angular 和 .Net6 的 Asp Net Core 项目。

[DisableCors]
[HttpGet("GetSales")]
        public IEnumerable<SaleDto> GetSales()
        {
            var result = _context.Sales.Select(x => new SaleDto
            {
                AccountName = x.Account.Name,
                CategoryName = x.Category.CategoryName,
                SaleDate = x.SaleDate,
                SaleId = x.SaleId,
                SaleValue = x.SaleValue,
            });
            return result;
        }

你需要在服务器上开启CORS。DisableCors会阻止这个功能。 - Daniel A. White
2
Postman不关心CORS,浏览器才关心。你明确禁用了该调用的CORS,那么为什么会想它不起作用呢? - derpirscher
测试了一下,没有禁用Cors,但仍然无法工作。 - visCode
那么,你配置了 CORS 吗?https://learn.microsoft.com/zh-cn/aspnet/core/security/cors?view=aspnetcore-6.0 - derpirscher
5个回答

8

在注册中间件时,您是否有适当的条目? 在 ASP.NET Core 中启用跨域请求 (CORS)。

您将需要添加本地主机和端口号。我相信端口号当前正在引起问题。如果两个站点在相同的端口号上,您可能不会遇到此问题。 另外,请参阅同一域上的 CORS 错误的答案。 同一域上的 CORS 错误?

此外,您想要启用 CORS 而不是禁用它。CORS 放宽了安全措施,因此您的代码可以跨越端口。


6
我所采用的方法是将文本放入HTML标签中。
app.UseCors(builder => builder
       .AllowAnyHeader()
       .AllowAnyMethod()
       .AllowAnyOrigin()
    );

之前

app.UseRouting();

app.UseEndpoints(endpoints =>
{
    endpoints.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");
});

在你的Program.csstartup.cs中,你可以修改配置。

1
根据微软文档,app.UseCors() 应该放在 app.UseRouting() 之后。 参见:https://learn.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-7.0#:~:text=The%20call%20to%20UseCors%20must%20be%20placed%20after%20UseRouting%2C%20but%20before%20UseAuthorization. - George Feakes

1
在 Appsetting.json 文件中 { "AllowOrigins": "https://localhost:4200" }
public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
       
        var allowOrigins = Configuration.GetValue<string>("AllowOrigins");
        services.AddCors(options =>
        {
            options.AddPolicy("CorsPolicy", builder =>
            {
                builder.WithOrigins(allowOrigins)
                    .AllowAnyHeader()
                    .AllowAnyMethod()
                  .AllowCredentials();
            });
            options.AddPolicy("AllowHeaders", builder =>
            {
                builder.WithOrigins(allowOrigins)
                        .WithHeaders(HeaderNames.ContentType, HeaderNames.Server, HeaderNames.AccessControlAllowHeaders, HeaderNames.AccessControlExposeHeaders, "x-custom-header", "x-path", "x-record-in-use", HeaderNames.ContentDisposition);
            });
        });
        services.AddSwaggerGen(c =>
        {
            c.SwaggerDoc("v1", new OpenApiInfo { Title = "DatingApp", Version = "v1" });
        });
        //authentication
        

                                                                                                                                                                                                                                            
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        app.UseMiddleware<ExceptionMiddleware>();
        app.UseSwagger();
        app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "DatingApp v1"));

        //if (env.IsDevelopment())
        //{
        //    app.UseDeveloperExceptionPage();
        //    }

        app.UseHttpsRedirection();

        app.UseRouting();

        app.UseCors("CorsPolicy");
        //authentication
        app.UseAuthentication();
        app.UseAuthorization();

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

}


奇怪的是,在上下文敏感的帮助中并没有弹出 .AllowCredentials ... 但当我相信你的答案并添加它时,它像冠军一样工作了... 所以谢谢!!!!! - Datum Geek

1
另一件要检查的事情是确保你的来源完全拼写正确。
我不知怎么回事,把"http://localhost:4200/"作为了来源,而不是"http://localhost:4200"。
花了很多小时才弄清楚这个问题。

0

我曾遇到类似问题,尝试从前端部分更改标题来进行调用,直接更改到控制器,但对我有效的是更改API项目中的Start.cs文件并添加以下内容。建议您先在本地主机上尝试,然后再将更改部署到实际拥有API的位置。

public class Startup
{
    private readonly string _MyCors = "MyCors";
    .
    .
    .
    public void ConfigureServices(...)
    {
        .
        .
        .
        //Under your services.AddControllers();
        services.AddCors(options =>
        {
            options.AddPolicy(name: _MyCors, builder =>
            {
                //for when you're running on localhost
                builder.SetIsOriginAllowed(origin => new Uri(origin).Host == "localhost") 
                .AllowAnyHeader().AllowAnyMethod();


                //builder.WithOrigins("url from where you're trying to do the requests")
            });
        });
    }
    public void Configure(.....)
    {
        //before the app.UseAuthorization & app.UseEndpoints
        app.UseCors(_MyCors);
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接