如何在路径中检索站点范围的URL参数,而不会使用参数混乱每个控制器操作?我的问题类似于
this question,但我想避免使用ModelBinder的混乱. IE浏览器.在Global.asax.cs中:
routes.MapRoute( "Default",// Route name "{sitename}/{controller}/{action}/{id}",new { sitename = "",controller = "SomeController",action = "Index",id = "" } );
所以,而不是SomeController类中的以下内容:
public ActionResult Index(string sitename) { SiteClass site = GetSite(sitename); ... return View(site.Getviewmodel()); }
我宁愿拥有以下内容:
public ActionResult Index() { SiteClass site = CurrentSite; // where CurrentSite has already retrieved data based on unique URL sitename parameter. ... return View(site.Getviewmodel()); }
也许这可以通过控制器范围的动作过滤器来实现? OnActionExecuting?
解决方法
首先添加一个到Global.aspx.cs的路由来传递{sitename}参数:
routes.MapRoute( "Sites",// URL with parameters new { sitename = "",controller = "Home",id = "" } // Parameter defaults );
public class BaseController: Controller { public string SiteName = ""; protected override void OnActionExecuting(ActionExecutingContext filterContext) { HttpRequestBase req = filterContext.HttpContext.Request; SiteName = filterContext.RouteData.Values["sitename"] as string; base.OnActionExecuting(filterContext); } }
并在派生控制器中使用:
public class HomeController: BaseController { public ActionResult Index() { ViewData["SiteName"] = SiteName; return View(); } }