代码之家  ›  专栏  ›  技术社区  ›  Matthias Burger

使用http.routeattribute路由可选参数

  •  1
  • Matthias Burger  · 技术社区  · 7 年前

    我有一个带有两个必需参数和几个可选参数的操作:

    [HttpGet]
    public IHttpActionResult GetUsers(DateTime dateFrom, DateTime dateTo, string zipcode, int? countryId)
    {
        using (DataHandler handler = new DataHandler())
            return Ok(handler.GetUsers(dateFrom, dateTo).ToList());
    }
    

    我想要一个像这样的网址:

    /api/getusers/2018-12-03T07:30/2018-12-03T12:45?zipcode=4002&countryId=4
    

    zipcode countryId 是可选的,将与 ? -thigy。所需参数 dateFrom dateTo 将添加 /

    因此,以下URL也应该是可能的:

    /api/getusers/2018-12-03T07:30/2018-12-03T12:45?countryId=4
    /api/getusers/2018-12-03T07:30/2018-12-03T12:45?zipcode=4002
    /api/getusers/2018-12-03T07:30/2018-12-03T12:45
    

    我试过一些路线,比如

    [Route("getusers/{dateFrom}/{dateTo}")]
    [Route("getusers/{dateFrom}/{dateTo}*")]
    [Route("getusers/{dateFrom}/{dateTo}**")]
    [Route("getusers/{dateFrom}/{dateTo}?zipcode={zipcode}&countryId={countryId}")]
    

    但他们都不起作用。 当我删除可选参数时,它会起作用,但我需要那些可选参数。

    你知道怎么做吗?

    1 回复  |  直到 7 年前
        1
  •  3
  •   Nkosi    7 年前

    使操作方法中的可选参数成为可选参数

    如果路由参数是可选的,则必须为方法参数定义默认值。

    //GET /api/getusers/2018-12-03T07:30/2018-12-03T12:45?countryId=4
    //GET /api/getusers/2018-12-03T07:30/2018-12-03T12:45?zipcode=4002
    //GET /api/getusers/2018-12-03T07:30/2018-12-03T12:45
    [HttpGet]
    [Route("getusers/{dateFrom:datetime}/{dateTo:datetime}")]
    public IHttpActionResult GetUsers(DateTime dateFrom, DateTime dateTo, string zipcode = null, int? countryId = null) {
        using (DataHandler handler = new DataHandler())
            return Ok(handler.GetUsers(dateFrom, dateTo).ToList());
    }
    

    参考文献 Attribute Routing in ASP.NET Web API 2