英文:
.NET 7 API catch-all route without breaking static files
问题
我们在.NET 7 API项目中使用属性路由。在启动中,我们在调用MapController()
之前调用了UseStaticFiles()
,类似于这样:
app
.UseDefaultFiles()
.UseStaticFiles()
.MapControllers();
app.Run();
我们尝试创建一个类似于以下的捕获所有路由:
[Route("/{**catchAll}")]
CatchNonExistingRoute()
{
//实现
}
这可以正常工作。然而,catchAll
路由优先于静态文件,这不是我们想要的。
是否有任何方法可以解决这个问题?
我已经尝试使用app.MapFallback
方法,但似乎也不能满足我的需求。
英文:
We are using attribute routing in a .NET 7 API project. In the startup we call UseStaticFiles()
before calling MapController()
. Something like this:
app
.UseDefaultFiles()
.UseStaticFiles()
.MapControllers();
app.Run();
We are trying to create a catch all route like this:
[Route("/{**catchAll}")]
CatchNonExistingRoute()
{
//implementation
}
This works. However, the catchAll route is taking precedence over the static files, which we don't want.
Is there any way around this?
I've been playing with the app.MapFallback
method, but this also doesn't seem to do what I want.
答案1
得分: 3
Try explicitly calling UseRouting
after UseStaticFiles
(AFAIK otherwise it is implicitly called before everything else which makes CatchNonExistingRoute
to have precedence over everything else):
app
.UseDefaultFiles()
.UseStaticFiles()
.UseRouting()
.MapControllers();
英文:
Try explicitly calling UseRouting
after UseStaticFiles
(AFAIK otherwise it is implicitly called before everything else which makes CatchNonExistingRoute
to have precedence over everything else):
app
.UseDefaultFiles()
.UseStaticFiles()
.UseRouting()
.MapControllers();
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论