如果路径以 '/api' 开头并且有一个文件映射为回退,如何返回 404?



我有一个asp.net core 6.0应用程序:

  • WeatherForecastController
  • index.htmlinwwwrootfolder.

我已将index.html配置为文件回退。这是program.csmain方法

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/api开始并且没有匹配的控制器动作时,我想返回404。

我尝试在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

开头

你可以在你的program .cs或Startup.cs中使用不同的IApplicationBuilder:

例如:

app.MapWhen(ctx => !ctx.Request.Path.StartsWithSegments("/api"), appBuilder =>
{
appBuilder.UseRouting();
appBuilder.UseEndpoints(ep =>
{
ep.MapFallbackToFile("index.html");
});
});

如果像这样添加app.UseMiddleware<ApiNotFoundMiddleware>();:

app.UseHttpsRedirection();
app.UseMiddleware<ApiNotFoundMiddleware>();
app.UseAuthorization();

如果你试图导航到任何带有/api

的东西,将返回404这是你想要达到的目标吗?