【问题标题】:Attribute Routing with empty parameters带空参数的属性路由
【发布时间】:2016-08-31 09:46:47
【问题描述】:

我使用以下代码asp core P>

    [HttpGet]
    [Route("all/{q:alpha}/{begin:int}/{pageSize:int}/{sortBy:alpha}/{sortOrder:alpha}")]
    public IActionResult GetAll(string q, int begin, int pageSize, string sortBy, bool sortOrder)
    {
        return Json(_repository.GetItemsByPage(q, begin, pageSize, sortBy, sortOrder));
    }

应该是可能的“Q”是空的。如果没有属性路由一切工作正常。以下请求有效:

http://localhost/api/all/?q=&begin=1&pagesize=3&sortBy=title&sortOrder=false

通过在适当位置的路由的请求中的属性是:

 http://localhost/api/all//1/3/title/false

如何使它具有空值(q)中工作的? P>

【问题讨论】:

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


    【解决方案1】:

    根据我的建议,可选参数必须放在末尾。

    [HttpGet]
    
    [Route("all/{begin:int}/{pageSize:int}/{sortBy:alpha}/{sortOrder:alpha}/{q:alpha}")]
    public IActionResult GetAll(string q, int begin, int pageSize, string sortBy, bool sortOrder)
     {
       return Json(_repository.GetItemsByPage(q, begin, pageSize, sortBy, sortOrder));
     }
    

    这样你的两个网址都可以工作。

    http://localhost/api/all/?q=&begin=1&pagesize=3&sortBy=title&sortOrder=false
    
    http://localhost/api/all/1/3/title/false
    
    http://localhost/api/all/1/3/title/false/value of q
    

    现在,如果您的方法有多个可选参数,则有多种方法可以解决问题。

     http://localhost/api/all/1/3/title/false?q=1&optinal2=value
    

    或者创建第二个 API 方法。

    【讨论】:

    • 谢谢。我将可选参数移到最后并使用:{q:alpha?}
    猜你喜欢
    • 2015-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-02
    • 1970-01-01
    相关资源
    最近更新 更多