[英]Web api routing - cannot access default route?
我想在我的Web API中使用以下路由:
/ api / week / 2013/08/29 <-這是一個特定的星期
/ api / week / <-這是最后一周
{以及通往其他API控制器的一些默認路由}
我已經實現了一個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 /”工作。.我不認為我的操作存在問題(或事實是,可選參數),但路由似乎是錯誤的,但我不知道為什么...
謝謝你的幫助!
編輯:
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);
}
通過更改您的DateTime? week
DateTime? week
參數的默認值為null,您的兩條路由均有效:
[WeekFilter]
public IEnumerable<Week> Get(DateTime? week = null)
{
return null;
}
當您使用api/week
調用控制器時,action方法上的week參數為null
。 如果年和月為空,則可以通過修改WeekFilter
來初始化星期來更改此設置。
如果您使用/api/week/2013/8/13
調用它,那么一切都會按預期進行。
我發現了我的錯誤。
在我的全球Asax中,我有:
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
WebApiConfig.RegisterRoutes(GlobalConfiguration.Configuration);
BundleConfig.RegisterBundles(BundleTable.Bundles);
但是顯然Web Api路由的位置很重要,我將其更改為
WebApiConfig.RegisterRoutes(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
現在就可以了!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.