我想在我的 web api 中使用以下路由:
/api/week/2013/08/29 <-- 这是特定的一周
/api/week/ <-- 这是最后一周
{以及到其他 api-controllers 的一些默认路由}
我已经实现了一个正确检索信息的 Get 函数,但是我的路由有问题。
我已经声明了以下内容:
config.Routes.MapHttpRoute(
name: "WeekRoute",
routeTemplate: "api/week/{year}/{month}/{day}",
defaults: new { controller = "Week" },
constraints: new { year = @"\d{1,4}", month = @"[1-9]|1[0-2]", day = @"[0-9]|[0-2][0-9]|3[0-1]" }
);
// I don't think I'd even need this one, but I put it here for specificity
config.Routes.MapHttpRoute(
name: "DefaultWeek",
routeTemplate: "api/week",
defaults: new { controller = "Week", action="Get" }
);
config.Routes.MapHttpRoute(
name: "ApiDefault",
routeTemplate: "api/{controller}/{id}",
defaults: new { controller = "Week", id = RouteParameter.Optional }
);
我的行动:
[WeekFilter] // This filters out the year/month/day string and creates a DateTime
public IEnumerable<Week> Get(DateTime? week = null){...}
我已经尝试了一段时间,但我似乎无法让“/api/week/”工作..我认为我的行为没有问题(或者它有可选参数),但路由似乎是错误的,但我不知道为什么......
谢谢你的帮助!
编辑:
周过滤器:
public class WeekFilterAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
var year = actionContext.ControllerContext.RouteData.Values["year"] as string;
var month = actionContext.ControllerContext.RouteData.Values["month"] as string;
if (!string.IsNullOrEmpty(year) && !string.IsNullOrEmpty(month))
{
var day = actionContext.ControllerContext.RouteData.Values["day"] as string;
if (string.IsNullOrEmpty(day))
day = "1";
var datum = new DateTime(int.Parse(year), int.Parse(month), int.Parse(day));
actionContext.ActionArguments["week"] = datum;
}
base.OnActionExecuting(actionContext);
}
}
那个行动:
[WeekFilter]
public IEnumerable<Week> Get(DateTime? week = null)
{
return HandlerLocator.GetQueryHandler<IGetWeeksDataHandler>().Execute(week);
}