Nug*_*ugs 3 c# asp.net-web-api-routing .net-core .net-core-2.2
我有一个带有一堆现有控制器的 Core 2.2 API。我现在要做的是添加一个新的控制器,它的作用类似于一个通用路由,但仅适用于该控制器(并且不会干扰现有控制器的路由)。
在我现有的控制器中,我将路由定义为控制器属性
[Route("api/[controller]")]
[ApiController]
public class SandboxController : ControllerBase
{
[HttpGet("Hello")]
public IEnumerable<string> Hello()
{
return new string[] { "Hello World", TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time")).ToString()};
}
}
Run Code Online (Sandbox Code Playgroud)
对于这个新的“catchall”控制器,我需要它能够捕获路由到它的任何 Get、Post、Put、Delete。例如,这个控制器路由是 ../ api/catchall。如果有人在哪里发帖到 ../api/catchall/ some/random/unknown/route我试图抓住这个并将其路由到 ../api/catchall/ post。
到目前为止,我完全没有成功。这是我到目前为止得到的:
在我的 Startup.cs
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseAuthentication();
...
app.UseMvc(routes =>
{
routes.MapRoute("default", "{controller=Sandbox}/{action=Hello}/{id?}");
routes.MapRoute(
name: "catchall",
template: "{controller}/{*.}",
defaults: new { controller = "catchall", action = "post" });
});
Run Code Online (Sandbox Code Playgroud)
和 catchall 控制器:
[Route("api/[controller]")]
[ApiController]
public class CatchallController : ControllerBase
{
[HttpPost("post", Order = int.MaxValue)]
public IActionResult Post([FromBody] string value)
{
return Content("{ \"name\":\"John Doe\", \"age\":31, \"city\":\"New York\" }", "application/json");
}
}
Run Code Online (Sandbox Code Playgroud)
关于如何让它发挥作用的任何想法?
捕获所有使用*or**语法指定的路由。放置[Route("{**catchall}")]在您想要成为捕获所有操作的操作上。这将为所有以 Controller 路由属性中指定的前缀为前缀的路由创建一个捕获所有路由。
[Route("api/[controller]")]
[ApiController]
public class CatchallController : ControllerBase
{
[Route("{**catchAll}")]
[HttpPost("post", Order = int.MaxValue)]
public IActionResult Post([FromBody] string value, string catchAll)
{
return Content("{ \"name\":\"John Doe\", \"age\":31, \"city\":\"New York\" }", "application/json");
}
}
Run Code Online (Sandbox Code Playgroud)
在上面的例子中,这将捕获api/catchall/anything/following/it并将字符串 catchAll 设置为anything/following/it
如果要设置站点范围的捕获所有路由,可以使用绝对 url
[Route("/{**catchAll}")]
public IActionResult CatchAll(string catchAll)
{
}
Run Code Online (Sandbox Code Playgroud)
这将捕获与任何其他指定路线不匹配的任何路线。
| 归档时间: |
|
| 查看次数: |
4468 次 |
| 最近记录: |