允许在.NET 7中允许所有来源

huangapple go评论62阅读模式
英文:

define Allow all origins in .NET 7

问题

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

In dotnet 3, the code that allows all origins in the startup.cs was:

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

This code gives me access to my API (the Angular and the Dotnet are both on the same computer) via Angular requests.

Today I try to generate 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 response headers coming from the Dotnet.

In summary: What is the equivalent code in Dotnet 7 that allows any origin and avoids CORS error?

Edited after Qing Guo's 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 middleware of app.UseHttpsRedirection();

P.S. Thanks Qing Guo for the helpful answers and references (I can't rate still).

英文:

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 =&gt; x
              .AllowAnyMethod()
              .AllowAnyHeader()
              .SetIsOriginAllowed(origin =&gt; 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 =&gt;
{
    var MyAllowSpecificOrigins = &quot;_MyAllowSubdomainPolicy&quot;;
    options.AddPolicy(name: MyAllowSpecificOrigins,
        policy =&gt;
        {
            policy.WithOrigins(&quot;http://localhost:4200&quot;)
                .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 = &quot;_myAllowSpecificOrigins&quot;;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddCors(options =&gt;
{

    options.AddPolicy(name: MyAllowSpecificOrigins,
        policy =&gt;
        {
            policy.WithOrigins(&quot;http://localhost:4200&quot;)
                .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&lt;Context&gt;(options =&gt; options
                .UseSqlServer(builder.Configuration
                .GetConnectionString(&quot;myProject&quot;)));

builder.Services.Configure&lt;ForwardedHeadersOptions&gt;(options =&gt;
{
    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

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

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)

答案1

得分: 1

尝试:

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();

参考:

CORS 使用命名策略和中间件

英文:

Try:

var  MyAllowSpecificOrigins = &quot;_myAllowSpecificOrigins&quot;;

var builder = WebApplication.CreateBuilder(args);

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


...app.UseRouting();

app.UseCors(MyAllowSpecificOrigins);

app.UseAuthorization();

refer to:

CORS with named policy and middleware

huangapple
  • 本文由 发表于 2023年6月19日 17:45:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/76505435.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定