我想在我的网络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 /”一个工作..我不认为我的行动有问题(或者事实是它有一个可选参数),但路由似乎是错误的,但我无法弄清楚为什么......
感谢您的帮助!
编辑:
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);
}
答案 0 :(得分:0)
通过将DateTime? week
参数更改为默认值为null,您的路由都正常工作:
[WeekFilter]
public IEnumerable<Week> Get(DateTime? week = null)
{
return null;
}
当您使用api/week
致电控制器时,您的操作方法的周参数为null
。如果年份和月份为空,您可以通过修改WeekFilter
初始化周来更改此项。
如果您使用/api/week/2013/8/13
调用它,一切都按预期工作。
答案 1 :(得分:0)
我发现了我的错误。
在我的全球性asax中,我有:
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
WebApiConfig.RegisterRoutes(GlobalConfiguration.Configuration);
BundleConfig.RegisterBundles(BundleTable.Bundles);
但显然网络Api路由的位置很重要,我将其更改为
WebApiConfig.RegisterRoutes(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
现在它有效!