我想在我的網頁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