我在IIS上有许多指向同一个ASP.NET MVC应用程序的主机名。
www.domain.com
www.domain.co.uk
www.domain.net
...
当我设置如下地图路线时,如何获得顶级域名(例如" .com")?
Shared Sub RegisterRoutes(ByVal routes As RouteCollection)
routes.IgnoreRoute("{resource}.axd/{*pathInfo}")
' MapRoute takes the following parameters, in order:
' (1) Route name
' (2) URL with parameters
' (3) Parameter defaults
routes.MapRoute( _
"Default", _
"{controller}/{action}/{id}", _
New With {.controller = "Home", .action = "Index", .id = UrlParameter.Optional} _
)
End Sub
答案 0 :(得分:2)
您需要创建自定义路线。只需继承Route
,覆盖GetRouteData
并包含适用于TLD的路由信息。
http://msdn.microsoft.com/en-us/library/system.web.routing.route.getroutedata.aspx
示例强>
路线:
public class RouteWithTld : Route
{
public RouteWithTld(string url, IRouteHandler routeHandler) : base(url, routeHandler)
{
}
public RouteWithTld(string url, RouteValueDictionary defaults, IRouteHandler routeHandler) : base(url, defaults, routeHandler)
{
}
public RouteWithTld(string url, RouteValueDictionary defaults, RouteValueDictionary constraints, IRouteHandler routeHandler) : base(url, defaults, constraints, routeHandler)
{
}
public RouteWithTld(string url, RouteValueDictionary defaults, RouteValueDictionary constraints, RouteValueDictionary dataTokens, IRouteHandler routeHandler) : base(url, defaults, constraints, dataTokens, routeHandler)
{
}
public override RouteData GetRouteData(HttpContextBase httpContext)
{
var baseData = base.GetRouteData(httpContext);
int pos = httpContext.Request.Url.Host.LastIndexOf('.');
string tld;
if (pos == -1)
{
if (httpContext.Request.Url.Host == "localhost")
tld = "com";
else
{
throw new InvalidOperationException("You need to handle this case.");
}
}
else
tld = httpContext.Request.Url.Host.Substring(pos + 1);
baseData.Values.Add("tld", tld);
return baseData;
}
}
在global.asax中映射它:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
/*routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
* */
var defaults =
new RouteValueDictionary(new {controller = "Home", action = "Index", id = UrlParameter.Optional});
routes.Add(new RouteWithTld("{controller}/{action}/{id}", defaults, new MvcRouteHandler()));
}
访问控制器中的参数:
public class HomeController : Controller
{
public ActionResult Index()
{
ViewBag.Message = "Welcome to ASP.NET MVC. TLD: " + RouteData.Values["tld"];
return View();
}
public ActionResult About()
{
return View();
}
}