我试图了解MVC 5中路由配置是如何工作的。
我的应用程序有以下结构:
BaseCRUDController
public class BaseCRUDController<TEntity, TEntityViewModel> : Controller
where TEntity : class
where TEntityViewModel : class
{
private readonly IBaseService<TEntity> baseService;
public BaseCRUDController(IBaseService<TEntity> service)
{
this.baseService = service;
}
[HttpGet]
public virtual ActionResult Index()
{
IList<TEntityViewModel> entities = baseService.FindFirst(10).To<IList<TEntityViewModel>>();
return View(entities);
}}
CountriesController
[RouteArea("management")]
[RoutePrefix("countries")]
public class CountriesController : BaseCRUDController<Country, CountryViewModel>
{
private readonly ICountryService service;
public CountriesController(ICountryService service)
: base(service)
{
this.service = service;
}
}我想做的事情很简单:http://myapplication.com/management/countries。我有许多其他控制器,超类是基本控制器。我这样做是为了避免代码重复,因为控制器具有类似的结构。
问题是:
我怎样才能解决这些问题?
我的路由配置是这样的:
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapMvcAttributeRoutes();
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}发布于 2015-03-30 03:25:25
玩了一会儿后,我设法让它开始工作了。
问题是当您使用属性路由时,没有指定默认路由参数。
例如,在Default路由中,默认设置为controller = "Home", action = "Index"。因此,如果要调用http://myapplication.com/,路由引擎将自动默认为/Home/Index/,依此类推。
但是,属性路由无法知道您想要默认为Index操作(或任何其他操作)。
为了解决这个问题,将Route属性添加到CountriesController中,如下所示:
[RouteArea("management")]
[RoutePrefix("countries")]
[Route("{action=Index}")] // this defines the default action as Index
public class CountriesController : BaseCRUDController<Country, CountryViewModel>
{
private readonly ICountryService service;
public CountriesController(ICountryService service)
: base(service)
{
this.service = service;
}
}另外,对于将来的参考,菲尔·哈克的路径调整器对于解决路由问题是非常有帮助的。
发布于 2015-03-30 03:26:04
您是否为您的控制器定义了区域(管理)?如果你尝试没有区域,这是不是得到正确的重定向?
https://stackoverflow.com/questions/29336174
复制相似问题