views:

46

answers:

1

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  A: 

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();
    }
}
FreshCode
Not sure if this is the best way, but it beats cracking open Application_BeginRequest.
FreshCode
In my implementation I don't use a string for SiteName. Instead I store the actual Site or Site data, which comes in handy for a multi-site application.
FreshCode