具有空参数的属性路由

时间:2016-08-31 09:46:47

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

我在asp core

中使用以下代码
    [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)?

1 个答案:

答案 0 :(得分:0)

根据我的建议,可选参数必须结束。

[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方法。