如何在路径中检索站点范围的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?
答案 0 :(得分:4)
routes.MapRoute(
"Sites", // Route name
"{sitename}/{controller}/{action}/{id}", // URL with parameters
new { sitename = "", controller = "Home", action = "Index", 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();
}
}
答案 1 :(得分:0)
也许我误解了这个问题,但为什么不在控制器操作中简单地执行以下操作:
var sitename = RouteData.Values["sitename"] as string;
我不明白为什么你需要覆盖OnActionExecuting(per @ pate的答案),当你需要它时可以检索它。
也没有必要创建基类并从中获取所有内容。如果您反对将该行复制到每个控制器的每个操作方法中,为什么不创建扩展方法?