0

i try to connect angular project to .NET 7 API.

in dotnet 3 the code that allow all origins in the startup.cs was:

 app.UseCors(x => x
              .AllowAnyMethod()
              .AllowAnyHeader()
              .SetIsOriginAllowed(origin => true) // allow any origin

this code give me eccess to my api (the angular and the dotnet ar both on the same computer) via angular request.

today i try to genareate the same code, or at least to allow access only to the angular address, for now with no success.

this is the code in the program.cs i tried to run:

builder.Services.AddCors(options =>
{
    var MyAllowSpecificOrigins = "_MyAllowSubdomainPolicy";
    options.AddPolicy(name: MyAllowSpecificOrigins,
        policy =>
        {
            policy.WithOrigins("http://localhost:4200")
                .SetIsOriginAllowedToAllowWildcardSubdomains();
        });
});

and then in the middleware section:

app.UseCors();
app.UseAuthorization();

i still get the CORS error with no any response headers coming from the dotnet.

in summary: what is the equivalent code in dotnet 7 that allow any origin and avoiding CORS error?

edited after Qing Guo response:

the CORS error still appears : I am attaching all the information and codes that might help.

complete program.cs

using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using myProjAPI.Data;
using Microsoft.AspNetCore.HttpOverrides;

var MyAllowSpecificOrigins = "_myAllowSpecificOrigins";
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddCors(options =>
{

    options.AddPolicy(name: MyAllowSpecificOrigins,
        policy =>
        {
            policy.WithOrigins("http://localhost:4200")
                .SetIsOriginAllowedToAllowWildcardSubdomains();
        });
});
// Add services to the container.

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI 
https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddDbContext<Context>(options => options
                .UseSqlServer(builder.Configuration
                .GetConnectionString("myProject")));

builder.Services.Configure<ForwardedHeadersOptions>(options =>
{
    options.ForwardedHeaders =
        ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
});


var app = builder.Build();

// Configure the HTTP request pipeline.
app.UseForwardedHeaders();
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
   
}
app.UseRouting();

app.UseCors(MyAllowSpecificOrigins);
app.UseAuthorization();

app.MapControllers();

app.Run();

here is the records from Chrome DevTools:

dev tools rec 0.1

dev tools rec 0.2

dev tools rec 0.3

this is my launchsetting.json

{
      "$schema": "https://json.schemastore.org/launchsettings.json",
      "iisSettings": {
        "windowsAuthentication": false,
        "anonymousAuthentication": true,
        "iisExpress": {
          "applicationUrl": "http://localhost:29309",
          "sslPort": 44358
        }
      },
      "profiles": {
        "http": {
          "commandName": "Project",
          "dotnetRunMessages": true,
          "launchBrowser": true,
          "launchUrl": "swagger",
          "applicationUrl": "http://localhost:5072",
          "environmentVariables": {
            "ASPNETCORE_ENVIRONMENT": "Development"
          }
        },
        "https": {
          "commandName": "Project",
          "dotnetRunMessages": true,
          "launchBrowser": true,
          "launchUrl": "swagger",
          "applicationUrl": "https://localhost:7106;http://localhost:5072",
          "environmentVariables": {
            "ASPNETCORE_ENVIRONMENT": "Development"
          }
        },
        "IIS Express": {
          "commandName": "IISExpress",
          "launchBrowser": true,
          "launchUrl": "swagger",
          "environmentVariables": {
            "ASPNETCORE_ENVIRONMENT": "Development"
          }
        }
      }
    }

thanks!

the solution

after deep internet digging i found the solution:

1.delete the headers section from the angular request.

2.remove the middlware of app.UseHttpsRedirection();

p.s. Thanks Qing Guo for the helpful answers and references (i can't rete still)

yosha
  • 1
  • 2
  • My guess would be that you have to reference the name of your policy, since you granted it a name. So you might have to use `app.UseCors("_MyAllowSubdomainPolicy");` – Maik Hasler Jun 19 '23 at 09:48

1 Answers1

1

Try:

var  MyAllowSpecificOrigins = "_myAllowSpecificOrigins";

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddCors(options =>
{
    options.AddPolicy(name: MyAllowSpecificOrigins,
                      policy  =>
                      {
                            policy.WithOrigins("http://localhost:4200")
            .SetIsOriginAllowedToAllowWildcardSubdomains();
                      });
});


...app.UseRouting();

app.UseCors(MyAllowSpecificOrigins);

app.UseAuthorization();

refer to:

CORS with named policy and middleware

Qing Guo
  • 6,041
  • 1
  • 2
  • 10
  • Hi @yosha , From your error message , please check with your post header Content-Type, you can have a look at [this answer](https://stackoverflow.com/questions/25727306/request-header-field-access-control-allow-headers-is-not-allowed-by-access-contr) to know more. – Qing Guo Jun 20 '23 at 02:54