我想在我的网页API以下途径:Web api路由 - 无法访问默认路由?
/API /周/ 2013/8月29日< - 这是一个特定的星期
/API /周/ < - 这是上周
{和其他API控制器一些默认路由}
我已经实现了一个获取函数正确检索的信息,但我有路由问题。
我已经声明如下:
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 /周/“一个工作..我不认为我的行动有问题(或它有一个可选参数的事实),但路由似乎是错误的,但我不明白为什么......
感谢您的帮助!
编辑:
的WeekFilter:
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);
}
你得到了什么样的错误?模糊的匹配? – Joel
404当我尝试/ api /或/ api/week /,/ api/week/2013/08/29给了我正确的结果 –
好吧,你的/ api/week/2013/08/29是否工作? – Joel