[英]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.