我有一個 asp.net core 6.0 應用程式:
WeatherForecastControllerindex.html在wwwroot檔案夾中。
我已配置index.html為檔案后備。這是main方法program.cs;
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
var app = builder.Build();
// Configure the HTTP request pipeline.
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.UseStaticFiles();
app.MapFallbackToFile("index.html");
app.Run();
}
我想在path開始時回傳 404/api并且沒有匹配的控制器操作。
我嘗試在之后添加中間件,app.MapControllers但中間件在控制器被呼叫之前執行,并且應用程式在嘗試呼叫 API 時總是回傳 404。
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
var app = builder.Build();
// Configure the HTTP request pipeline.
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.UseApiNotFound();
app.UseStaticFiles();
app.MapFallbackToFile("index.html");
app.Run();
}
這是中間件:
public class ApiNotFoundMiddleware
{
private readonly RequestDelegate next;
public ApiNotFoundMiddleware(RequestDelegate next)
{
this.next = next;
}
private static PathString prefix = "/api";
public Task InvokeAsync(HttpContext context)
{
if (context.Request.Path.StartsWithSegments(prefix))
{
context.Response.StatusCode = (int)HttpStatusCode.NotFound;
return Task.CompletedTask;
}
else
{
return this.next(context);
}
}
}
所以
如果路徑以 '/api' 開頭,沒有匹配的控制器操作并且有一個檔案映射為后備,如何回傳 404?
或者
有沒有辦法將后備檔案限制為不以開頭的路徑/api
uj5u.com熱心網友回復:
您可以針對 Progam.cs 或 Startup.cs 中的不同條件使用不同的 IApplicationBuilder:
例如:
app.MapWhen(ctx => !ctx.Request.Path.StartsWithSegments("/api"), appBuilder =>
{
appBuilder.UseRouting();
appBuilder.UseEndpoints(ep =>
{
ep.MapFallbackToFile("index.html");
});
});
uj5u.com熱心網友回復:
如果您app.UseMiddleware<ApiNotFoundMiddleware>();像這樣在此處添加:
app.UseHttpsRedirection();
app.UseMiddleware<ApiNotFoundMiddleware>();
app.UseAuthorization();
如果您嘗試使用 /api 導航到任何內容,這將回傳 404
這會是你想要達到的目標嗎?
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/485190.html
上一篇:組合框不會將視圖中的值傳遞給模型ASP.NETCore
下一篇:根據屬性回傳部分視圖剃須刀頁面
