ASP.NET MVC 路由 - 添加站点名称?
ASP.NET MVC routing - adding sitename?
所以,我需要让我的网站在路由中传递这个:
blah.com/sitename/{controller}/{action}/{id}
"sitename" 类似于 Vdir,但又不完全是。它将帮助我获得正确的数据等...对于给定的站点名称。
最好的方法是什么?我尝试在路由中这样做但没有成功,因为它找不到页面(这是我尝试直接进入登录页面时):
routes.MapRoute(
name: "Default",
url: "{sitename}/{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
用户将获得 url 类似 blah.com/somesite 或 blah.com/anothersite.
我只希望路由能够正常工作,但能够提取控制器周围的 "somesite" 或 "anothersite" 部分。
首先添加一条路由到Global.aspx.cs
传递一个{sitename}
参数:
routes.MapRoute(
"Sites", // Route name
"{sitename}/{controller}/{action}/{id}", // URL with parameters
new { sitename = "", controller = "Home", action = "Index", id = "" }// Parameter defaults
);
创建一个名为 BaseController
的新控制器。然后在基本控制器中添加以下简单代码:
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();
}
}
希望对您有所帮助。
所以,我需要让我的网站在路由中传递这个:
blah.com/sitename/{controller}/{action}/{id}
"sitename" 类似于 Vdir,但又不完全是。它将帮助我获得正确的数据等...对于给定的站点名称。
最好的方法是什么?我尝试在路由中这样做但没有成功,因为它找不到页面(这是我尝试直接进入登录页面时):
routes.MapRoute(
name: "Default",
url: "{sitename}/{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
用户将获得 url 类似 blah.com/somesite 或 blah.com/anothersite.
我只希望路由能够正常工作,但能够提取控制器周围的 "somesite" 或 "anothersite" 部分。
首先添加一条路由到Global.aspx.cs
传递一个{sitename}
参数:
routes.MapRoute(
"Sites", // Route name
"{sitename}/{controller}/{action}/{id}", // URL with parameters
new { sitename = "", controller = "Home", action = "Index", id = "" }// Parameter defaults
);
创建一个名为 BaseController
的新控制器。然后在基本控制器中添加以下简单代码:
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();
}
}
希望对您有所帮助。