我正在.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();
請求頭:
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

uj5u.com熱心網友回復:
您需要在 UseRouting 和 UseAuthorization 之間添加 app.UseCors
app.UseRouting();
app.UseCors("AllowAll");
app.UseAuthorization();
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/465792.html
標籤:。网 asp.net-web-api asp.net-core-webapi
下一篇:Zip已創建,但其中沒有檔案
