Passing a {sitename} parameter to MVC controller actions

拜拜、爱过 提交于 2019-12-18 12:49:04

问题


How can I retrieve a site-wide URL parameter in a route without cluttering each controller action with a parameter? My question is similar to this question, but I want to avoid the ModelBinder clutter. Ie. in Global.asax.cs:

routes.MapRoute(
    "Default", // Route name
    "{sitename}/{controller}/{action}/{id}",
    new { sitename = "", controller = "SomeController", action = "Index", id = "" }    );

So, instead of the following in SomeController class:

public ActionResult Index(string sitename)
{
    SiteClass site = GetSite(sitename);
    ...
    return View(site.GetViewModel());
}

I would rather have the following:

public ActionResult Index()
{
    SiteClass site = CurrentSite; // where CurrentSite has already retrieved data based on unique URL sitename parameter.
    ...
    return View(site.GetViewModel());
}

Perhaps this can be achieved with controller-wide action filter? OnActionExecuting?


回答1:


First add a route to Global.aspx.cs to pass a {sitename} parameter:

routes.MapRoute(
    "Sites", // Route name
    "{sitename}/{controller}/{action}/{id}", // URL with parameters
    new { sitename = "", controller = "Home", action = "Index", id = "" } // Parameter defaults
);

Then add the following simple code inside a base controller:

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);
    }
}

And use in your derived controller:

public class HomeController: BaseController
{
    public ActionResult Index()
    {
        ViewData["SiteName"] = SiteName;
        return View();
    }
}



回答2:


Perhaps I misunderstand the question, but why not simply do the following inside your controller action:

var sitename = RouteData.Values["sitename"] as string;

I don't understand why you would need to override OnActionExecuting (per @pate's answer) when you can retrieve the value when you need it.

There's also no need to create a base class and have everything derive from it. If you object to copying that line into every action method of every controller, why not create an extension method?



来源:https://stackoverflow.com/questions/2237375/passing-a-sitename-parameter-to-mvc-controller-actions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!