.NET 7 API catch-all路由,不破坏静态文件。

huangapple go评论49阅读模式
英文:

.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();

huangapple
  • 本文由 发表于 2023年4月20日 02:01:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/76057577.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定