.Net WebApi - CORS 缺少允许来源
.Net WebApi - CORS are Missing Allow Origin
我正在 .Net 中做我的第一个 WebAPI 项目,对于前端,我使用的是 React。我刚刚实施了 JWT 授权,我注意到当我 运行 反应服务器时,帖子不再获取。
我试图查看问题是什么,我注意到状态为“已阻止”和“已转移”->“CORS 缺少允许来源”。
我该如何解决这个问题?
提前谢谢你。
var builder = WebApplication.CreateBuilder(args);
// DB set
var connectionString = builder.Configuration.GetConnectionString("DBConnection");
builder.Services.AddDbContext<FireStoneDbContext>(options =>
options.UseSqlServer(connectionString));
// CORS
builder.Services.AddCors(options =>
{
options.AddPolicy("AllowAll", builder =>
{
builder.AllowAnyMethod()
.AllowAnyOrigin()
.AllowAnyHeader();
});
});
// Add services to the container.
builder.Services.AddControllers();
// Register services
builder.Services.AddTransient<IPostService, PostService>();
builder.Services.AddTransient<IAuthService, AuthService>();
builder.Services.AddTransient<IUsersService, UsersService>();
// Register Repositories
builder.Services.AddTransient<IPostRepository, PostRepository>();
builder.Services.AddTransient<IUsersRepository, UsersRepository>();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(options =>
{
options.SwaggerDoc("v1", new OpenApiInfo
{
Version = "v1",
Title = "FireStone API",
Description = "An ASP.NET Core Web API for managing FireStone",
TermsOfService = new Uri("https://example.com/terms"),
});
options.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme
{
Description = "Standard Authorization header using the Bearer scheme (\"bearer {token}\")",
In = ParameterLocation.Header,
Name = "Authorization",
Type = SecuritySchemeType.ApiKey
});
options.OperationFilter<SecurityRequirementsOperationFilter>();
// using System.Reflection;
var xmlFilename = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
options.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, xmlFilename));
});
// Authentication for the apis
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options => {
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(System.Text.Encoding.UTF8.GetBytes(builder.Configuration.GetSection("AppSettings:Token").Value)),
ValidateIssuer = false,
ValidateAudience = false,
};
});
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();
请求header:
GET /api/Post HTTP/1.1
Host: localhost:7187
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:99.0) Gecko/20100101 Firefox/99.0
Accept: application/json, text/plain, */*
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate, br
Origin: http://localhost:3000
Connection: keep-alive
Referer: http://localhost:3000/
Sec-Fetch-Dest: empty
Sec-Fetch-Mode: cors
Sec-Fetch-Site: same-site
Pragma: no-cache
Cache-Control: no-cache
HTTP/2 200 OK
content-type: application/json; charset=utf-8
date: Mon, 25 Apr 2022 12:06:34 GMT
server: Kestrel
X-Firefox-Spdy: h2
您需要在 UseRouting 和 UseAuthorization
之间添加 app.UseCors
app.UseRouting();
app.UseCors("AllowAll");
app.UseAuthorization();
我正在 .Net 中做我的第一个 WebAPI 项目,对于前端,我使用的是 React。我刚刚实施了 JWT 授权,我注意到当我 运行 反应服务器时,帖子不再获取。 我试图查看问题是什么,我注意到状态为“已阻止”和“已转移”->“CORS 缺少允许来源”。
我该如何解决这个问题? 提前谢谢你。
var builder = WebApplication.CreateBuilder(args);
// DB set
var connectionString = builder.Configuration.GetConnectionString("DBConnection");
builder.Services.AddDbContext<FireStoneDbContext>(options =>
options.UseSqlServer(connectionString));
// CORS
builder.Services.AddCors(options =>
{
options.AddPolicy("AllowAll", builder =>
{
builder.AllowAnyMethod()
.AllowAnyOrigin()
.AllowAnyHeader();
});
});
// Add services to the container.
builder.Services.AddControllers();
// Register services
builder.Services.AddTransient<IPostService, PostService>();
builder.Services.AddTransient<IAuthService, AuthService>();
builder.Services.AddTransient<IUsersService, UsersService>();
// Register Repositories
builder.Services.AddTransient<IPostRepository, PostRepository>();
builder.Services.AddTransient<IUsersRepository, UsersRepository>();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(options =>
{
options.SwaggerDoc("v1", new OpenApiInfo
{
Version = "v1",
Title = "FireStone API",
Description = "An ASP.NET Core Web API for managing FireStone",
TermsOfService = new Uri("https://example.com/terms"),
});
options.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme
{
Description = "Standard Authorization header using the Bearer scheme (\"bearer {token}\")",
In = ParameterLocation.Header,
Name = "Authorization",
Type = SecuritySchemeType.ApiKey
});
options.OperationFilter<SecurityRequirementsOperationFilter>();
// using System.Reflection;
var xmlFilename = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
options.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, xmlFilename));
});
// Authentication for the apis
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options => {
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(System.Text.Encoding.UTF8.GetBytes(builder.Configuration.GetSection("AppSettings:Token").Value)),
ValidateIssuer = false,
ValidateAudience = false,
};
});
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();
请求header:
GET /api/Post HTTP/1.1
Host: localhost:7187
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:99.0) Gecko/20100101 Firefox/99.0
Accept: application/json, text/plain, */*
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate, br
Origin: http://localhost:3000
Connection: keep-alive
Referer: http://localhost:3000/
Sec-Fetch-Dest: empty
Sec-Fetch-Mode: cors
Sec-Fetch-Site: same-site
Pragma: no-cache
Cache-Control: no-cache
HTTP/2 200 OK
content-type: application/json; charset=utf-8
date: Mon, 25 Apr 2022 12:06:34 GMT
server: Kestrel
X-Firefox-Spdy: h2
您需要在 UseRouting 和 UseAuthorization
之间添加 app.UseCorsapp.UseRouting();
app.UseCors("AllowAll");
app.UseAuthorization();