用于特定控制器操作的ASP.NET MVC 4路由

时间:2013-02-07 12:37:09

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

我有以下控制器/动作:

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

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

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

1 个答案:

答案 0 :(得分: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