简体   繁体   English

ASP.NET Core 6 中的“访问控制允许来源”

[英]'Access-Control-Allow-Origin' in ASP.NET Core 6

Tested in Postman and works fine.Postman中测试并且工作正常。 In Browser I get this Error:在浏览器中我得到这个错误:

Access to XMLHttpRequest at 'http://localhost:5081/api/Accounting/GetSales' from origin 'https://localhost:44426' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.从来源“https://localhost:44426”访问“http://localhost:5081/api/Accounting/GetSales”的 XMLHttpRequest 已被 CORS 策略阻止:不存在“Access-Control-Allow-Origin”header在请求的资源上。

Asp Net Core Project with Angular and.Net6 Asp Net Core 项目用 Angular 和.Net6

[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;
        }

Do you have the proper entries when you register the middleware?注册中间件时是否有正确的条目? https://docs.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-6.0 https://docs.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-6.0

You will need to add localhost and the port numbers.您将需要添加 localhost 和端口号。 I believe the port numbers are currently causing the issue right now.我相信端口号目前正在导致问题。 If both sites were on the same port number you might not get this issue.如果两个站点都在同一个端口号上,您可能不会遇到此问题。 Also, see the answers for CORS error on same domain.此外,请参阅同一域上 CORS 错误的答案。 CORS error on same domain? 同一域上的 CORS 错误?

I had a similar issue, I tried changing the header from the part of the front-end from where I was doing the calls and then directly to the controller but what worked for me was changing the Start.cs file of the API project and add the following.我有一个类似的问题,我尝试从我正在调用的前端部分更改 header,然后直接更改为 controller 但对我有用的是更改 ZDB974238714CA8DE6348A 项目的 Start.cs 文件和 add1D04CA8DE63483以下。 I recommend trying it first in localhost and then deploying the changes where you actually have the API.我建议先在 localhost 中尝试,然后将更改部署到您实际拥有 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);
    }
}

In Appsetting.json file { "AllowOrigins": "https://localhost:4200" }在 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();
        });
    }
}

} }

What works for me was putting对我有用的是把

app.UseCors(builder => builder
       .AllowAnyHeader()
       .AllowAnyMethod()
       .AllowAnyOrigin()
    );

before

app.UseRouting();

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

in your Program.cs or startup.cs在你的Program.csstartup.cs

then you can alter your configrations然后你可以改变你的配置

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 ASP.NET 5: Access-Control-Allow-Origin 响应 - ASP.NET 5: Access-Control-Allow-Origin in response ASP.NET Core CORS WebAPI:没有 Access-Control-Allow-Origin 标头 - ASP.NET Core CORS WebAPI: no Access-Control-Allow-Origin header 在Asp.net Core 2.1的Angular 6中不存在“ Access-Control-Allow-Origin”标头 - No 'Access-Control-Allow-Origin' header is present Angular 6 with Asp.net Core 2.1 ASP.Net核心WebAPI - 请求的资源上没有“Access-Control-Allow-Origin”标头 - ASP.Net Core WebAPI - No 'Access-Control-Allow-Origin' header is present on the requested resource CORS asp.net 核心 webapi - 缺少 Access-Control-Allow-Origin 标头 - CORS asp.net core webapi - missing Access-Control-Allow-Origin header ASP.NET Core CORS WebAPI:不保留 Access-Control-Allow-Origin 标头 - ASP.NET Core CORS WebAPI: persist no Access-Control-Allow-Origin header 不存在“Access-Control-Allow-Origin”标头 - 面向 .net 框架 4.5.1 的 asp.net 核心 Web api - No 'Access-Control-Allow-Origin' header is present - asp.net core web api targeting .net framework 4.5.1 在Access-Control-Allow-Origin标头中找不到源[域]。 ASP .NET CORE API MVC - Origin [domain] not found in Access-Control-Allow-Origin header. ASP .net CORE API mvc ASP.NET Core Web Api发送Access-Control-Allow-Origin:null CORS头和chrome是错误的,如何修复? - ASP.NET Core Web Api sending Access-Control-Allow-Origin: null CORS header and chrome is erroring, how to fix? React+ASP.NET.Core:请求的资源上不存在“Access-Control-Allow-Origin”标头 - React+ASP.NET.Core : No 'Access-Control-Allow-Origin' header is present on the requested resource
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM