且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

传递一个{SITENAME}参数MVC控制器动作

更新时间:2023-02-25 17:17:00

首先添加路由到Global.aspx.cs传递一个{SITENAME}参数:

  routes.MapRoute(
    网站,//路线名称
    {网站名称} / {控制器} / {行动} / {ID},// URL带参数
    新{网站名称=,控制器=家,行动=索引,ID =} //参数默认
);

然后添加以下简单code基本控制器内:

 公共类BaseController:控制器
{
    公共字符串网站名称=;    保护覆盖无效OnActionExecuting(ActionExecutingContext filterContext)
    {
        HTT prequestBase REQ = filterContext.HttpContext.Request;
        网站名称= filterContext.RouteData.Values​​ [网站名称作为字符串;
        base.OnActionExecuting(filterContext);
    }
}

而在你的派生的控制器使用方法:

 公共类HomeController的:BaseController
{
    公众的ActionResult指数()
    {
        计算机[网站名称] =网站名称;
        返回查看();
    }
}

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?

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