【问题标题】:How to do conditional routing in asp.net core?如何在 asp.net core 中进行条件路由?
【发布时间】:2020-11-02 19:49:08
【问题描述】:

我想创建如下所示的路由

[HttpPost("device/{id}/disable")]
[HttpPost("device/{id}/enable")]
public async Task SetDevice(stirng id, bool state)

当用户点击“device/{id}/disable”时,状态变量会自动赋值为false,反之亦然。我怎样才能做到这一点?谢谢

【问题讨论】:

    标签: asp.net-core routes attributerouting


    【解决方案1】:

    你有两个或更多的选择:

    使用路线名称

    [HttpPost("device/{id}/disable", Name = "disable_device")]
    [HttpPost("device/{id}/enable", Name = "enable_device")]
    public async Task SetDevice(stirng id){
       //...
       //get current route name here and implement your logic
       //...
    {
    

    如果您想知道如何在您的操作或剃刀视图中获取路线名称,请参阅get current route name

    或使用默认路由值:

    [HttpPost("device/{id}/disable/{state=false}")]
    [HttpPost("device/{id}/enable/{state=true}")]
    public async Task SetDevice(stirng id, bool state){
       //...
    {
    

    【讨论】:

    • 嗨,@Mohammad Barbast,我测试了你的解决方案,但是 [HttpPost("device/{id}/disable/{state?=false}")] 导致 RoutePatternException: The route parameter name 'state? '是无效的。路由参数名称必须非空且不能包含以下字符:'{'、'}'、'/'。这 '?'字符将参数标记为可选,并且只能出现在参数的末尾。 '*' 字符将参数标记为包罗万象,并且只能出现在参数的开头。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-21
    • 1970-01-01
    相关资源
    最近更新 更多