11

Tested in Postman and works fine. 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.

Asp Net Core Project with Angular and .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;
        }
visCode
  • 145
  • 1
  • 1
  • 7

5 Answers5

8

Do you have the proper entries when you register the middleware? Enable Cross-Origin Requests (CORS) in ASP.NET Core.

You will need to add localhost and the port numbers. 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 error on same domain?

Also, you want to enable CORS not disable it. CORS relaxes the security measures so your code can reach across ports.

Osama Rizwan
  • 615
  • 1
  • 7
  • 19
Eric Rohlfs
  • 1,811
  • 2
  • 19
  • 29
6

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

then you can alter your configrations

Wowo Ot
  • 1,362
  • 13
  • 21
  • 1
    According to the Microsoft docs `app.UseCors()` should be placed after `app.UseRouting()` See: 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 Jul 27 '23 at 09:12
1

In Appsetting.json file { "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();
        });
    }
}

}

  • strangely, .AllowCredentials didn't pop up in the context sensitive help... but when I trusted your answer and added it, it worked like a champ... so thanks !!!!! – Datum Geek May 19 '23 at 16:34
0

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. I recommend trying it first in localhost and then deploying the changes where you actually have the 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);
    }
}
0

Another thing to check is make sure your origin is spelled out exactly.

I had "http://localhost:4200/" as the origin somehow, instead of "http://localhost:4200".

Took a lot of hours to figure that out.

RMuesi
  • 2,852
  • 1
  • 24
  • 27