接受所有路径的ASP核心Api路由

时间:2019-05-28 00:17:01

标签: c# asp.net-mvc asp.net-web-api asp.net-core

试图找到某个地方,该地方解释了如何创建一个接受以特定名称开头的所有请求的路由。以及检索该请求的信息。因此,其中一个示例是创建一个test路由,该路由接受该路由的所有传入get请求。

理想情况下,可以支持

[Route("test")]
[ApiController]
public class TestController : ControllerBase
{
    // so that all request that start with 'test' go through this method
    public IActionRequest Process() {

    }
}

1 个答案:

答案 0 :(得分:0)

方法1:

[Route("test/{*any}")]
[ApiController]
public class TestController : Controller
{

    // so that all request that start with 'test' go through this method
    public IActionResult Process()
    {
        return new JsonResult(new{
            a = 1,
        });
    }

}

方法2:

注册全部路由:

app.UseMvc(routes =>
{
    routes.MapRoute(
        name: "default",
        template: "{controller=Home}/{action=Index}/{id?}");
    routes.MapRoute(
        name:"routeAny",
        template:"test/{*any}",
        defaults: new{
            Controller = "Test",
            Action = "Process",
        }
    );
});

并删除[ApiController]属性,因为它需要[Route()]

[ApiController]
public class TestController : Controller
{

    // so that all request that start with 'test' go through this method
    public IActionResult Process()
    {
        return new JsonResult(new{
            a = 1,
        });
    }

}