【问题标题】:How to define simple nested routes in ASP.NET Core如何在 ASP.NET Core 中定义简单的嵌套路由
【发布时间】:2022-01-18 04:21:16
【问题描述】:

是否有一种内置方式使用 ASP.NET Core 以与大多数其他语言相同的方式执行标准嵌套路由?我如何在 C# 中执行下面在 Go 和 JS 中显示的内容?

使用 chi 的 Go 示例:

r := chi.NewRouter()
r.Use(amiddleware)                           // Use some middleware
r.Group(func(r chi.Router) {                 // A group with further configuration
  r.Use(another)                             // Middleware that only applies to group
  r.Route("/trunk", func(r chi.Router) {     // First level of a nested route
    r.Route("/branch", func(r chi.Router) {  // Next level
      r.Get("/leaf", Leaf)                   // An endpoint
    })
  })
})

func Leaf(w http.ResponseWriter, r *http.Request) { ... }

http.ListenAndServe(":8080", r)  // Start it up

使用express的JS示例:

const app = express()
app.use(amiddleware)                          // Use middleware
app.use(Router().                             // A group with further configuration
  use(another).                               // Middleware that only applies to group
  use('/trunk', Router().                     // First level of a nested route
    use('/branch', Router().                  // Next level
      get('/leaf', leaf)                      // An endpoint
    )  
  )  
)

function leaf(req, res, next) { ... }

app.listen(8080)   // Start it up

【问题讨论】:

    标签: asp.net-core url-routing


    【解决方案1】:

    在 asp.net core 中,可以使用 route.MapRoute 规则。但是我个人觉得比go语言的路由规则要麻烦一些。没有像 gin 和 beego 这样简单的框架。你可以参考这个文档:

    https://docs.microsoft.com/en-us/aspnet/mvc/overview/older-versions-1/controllers-and-routing/creating-custom-routes-cs

    有一种更简单的方法可以像这样设置路由:

     [ApiController]
        [Route("api/[controller]")]
        public class HomeController : Controller
        {
    
    
            [HttpGet("{id}")]
            public string Test(int id)
            {
                return "Test";
            }
    
            [HttpGet("test/{id:int}")]
            public string Test1(int id)
            {
                return "Test1";
            }
        }
    

    测试网址:https://localhost:port/api/home/1

    Test1 网址:https://localhost:port/api/home/test/1

    更多路由使用参考:

    Routing to controller actions in ASP.NET Core

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-10-07
      • 1970-01-01
      • 2020-04-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多