我有一个 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()};
}
}
对于这个新的“包罗万象”的控制器我需要它能够捕获路由到它的任何 Get、Post、Put、Delete。例如这个控制器路由是../API/包罗万象。如果有人在 ../api/catchall/ 发帖一些/随机/未知/路线我试图抓住这个并将其路由到../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" });
});
还有包罗万象的控制器:
[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");
}
}
关于如何让它发挥作用有什么想法吗?