我有一個基于ASP.NET 5框架和Swagger UI撰寫的Web API。
當用戶向任何一個端點發出認證請求時,我得到404 "就像框架將用戶重定向到一個不存在的頁面!" 如果框架是由于未經授權的請求而自動重定向請求,我想改變這種行為,改為回傳401 json回應。如果不是這樣,我怎樣才能將回應代碼從404改為401作為JSON回應?
下面是啟動類的樣子
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers()。
services.AddSwaggerGen(span class="hljs-params">swagger =>)
{
swagger.SwaggerDoc("v1", new OpenApiInfo)
{
Version = "v1"/span>,
Title = "Student Athlete Wellness Tracker API",
Description = "為學生運動員健康追蹤器提供資料的API"。
});
swagger.AddSecurityDefinition("basic"/span>, new OpenApiSecurityScheme()
{
Name = "Authorization"/span>,
Type = SecuritySchemeType.Http。
Scheme = "basic"。
In = ParameterLocation.Header。
Description = "使用承載方案的基本授權頭。"。
});
swagger.AddSecurityRequirement(new OpenApiSecurityRequirement)
{
{
new OpenApiSecurityScheme {
{
Reference = new OpenApiReference ?
{
Type = ReferenceType.SecurityScheme,
Id = "basic".
}
},
Array.Empty<string>()
}
});
});
services.AddAuthentication("BasicAuthentication"/span>)
. AddScheme<AuthenticationSchemeOptions, BasicAuthenticationHandler> ("BasicAuthentication", null)。
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment()
{
app.UseDeveloperExceptionPage()。
}
else; }
{
app.UseExceptionHandler("/error") 。
app.UseHsts()。
}
app.UseSwagger()。
app.UseSwaggerUI(c => c. SwaggerEndpoint("/swagger/v1/swagger.json", "Student Athlete Wellness Trackers - v1") )。)
app.UseCors(x => x。 AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader()。
app.UseHttpsRedirection()。
app.UseRouting()。
app.UseAuthentication()。
app.UseAuthorization()。
app.UseEndpoints(endpoints =>)
{
endpoints.MapControllers()。
});
uj5u.com熱心網友回復:
我遇到了同樣的問題。
我添加了第二個選項。
我添加了第二個選項行,這就解決了問題。
我添加了第二個選項行。
services.AddAuthentication(options => //span>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme。
})
你可以閱讀官方檔案來了解更多:https://docs.microsoft.com/en-us/aspnet/core/security/authentication/?view=aspnetcore-5.0
示例:Web api core在添加Authorize屬性時回傳404
uj5u.com熱心網友回復:
為了解決這個問題,我改變了
services.AddAuthentication("BasicAuthentication"/span>)
.AddScheme<AuthenticationSchemeOptions, BasicAuthenticationHandler>("BasicAuthentication", null)。
to
services.AddAuthentication(opts => //span>
{
opts.DefaultAuthenticateScheme = "BasicAuthentication"/span>。
opts.DefaultChallengeScheme = "BasicAuthentication"。
opts.DefaultScheme = "BasicAuthentication"。
opts.AddScheme<BasicAuthenticationHandler>("BasicAuthentication", null) 。
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/306972.html
標籤:
上一篇:試圖從gridview控制元件中獲取資料,但得到"methodnameexpected"編譯錯誤,是我的代碼結構不正確嗎?
