-2

我有以下控制器/动作:

public class SomeThingController
{
     IEnumerable<SomeThing> Search(DateTime minDate, DateTime maxDate, bool summaryOnly = true){}
}

想法是不必指定summaryOnly 参数,但必须指定minDate 和maxDate。

有人可以提供上述路线吗?

4

1 回答 1

3

您可以尝试以下路线:

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.Routes.MapHttpRoute(
            name: "Search",
            routeTemplate: "api/search/{minDate}/{maxDate}/{summaryOnly}",
            defaults: new { 
                summaryOnly = RouteParameter.Optional,  
                controller = "SomeThing", 
                action = "search" 
            }
        );

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}

进而:

public class SomeThingController : ApiController
{
    [HttpGet]
    public IEnumerable<SomeThing> Search(DateTime minDate, DateTime maxDate, bool summaryOnly = true)
    {
        ...
    }
}

然后你可以像这样请求这个端点:

/api/search/2013-02-08/2013-02-10/

或者:

/api/search/2013-02-08/2013-02-10/false
于 2013-02-07T13:04:48.133 回答