ASP.NET MVC 实现二级域名
2016-06-27 15:05
706 查看
自从微软发布 ASP.NET MVC 和routing engine (System.Web.Routing)以来,就设法让我们明白你完全能控制URL和routing,只要与你的application path相结合进行扩展,任何问题都迎刃而解。如果你需要在所处的域或者子域处理数据标记的话,强制使用Default。
遗憾的是,ASP.NET MVC是基于虚拟目录的,在实际项目却有各种各样的需求方案。
例如:
1:应用程序是多语言的,像cn.example.com应该被匹配到“www.{language}example.com”路由上。
2:应用程序是多用户的,像username.example.com应该被匹配到“www.{clientname}.example.com”路由上。
3:应用程序是多子域的,像mobile.example.com应该被匹配到"www.{controller}.example.com/{action}....” 。
坐下来,深呼吸,开始我们ASP.NET MVC的神奇之旅吧。
定义routes
下面是我们定义简单的route,不带任何controller控制的route:打算用controller 和action完全控制域名?
routes.Add("DomainRoute", new DomainRoute(
"{controller}-{action}.example.com", // Domain with parameters
"{id}", // URL with parameters
new { controller = "Home", action = "Index", id = "" } // Parameter defaults
));
接下来是多语言route:
routes.Add("DomainRoute", new DomainRoute(
"{language}.example.com", // Domain with parameters
"{controller}/{action}/{id}", // URL with parameters
new { language = "en", controller = "Home", action = "Index", id = "" } // Parameter defaults
));
HtmlHelper 扩展方法
因为我们不希望所有的URL所产生HtmlHelper ActionLink要使用full URLs,第一件事我们会添加一些新的ActionLink,其中载有boolean flag是否要full URLs或没有。利用这些,现在您可以添加一个链接到一个Action如下:<%= Html.ActionLink("About", "About", "Home", true)%>
跟你以往的习惯没有什么不同,不是吗?
以下是一小段代码:
public static class LinkExtensions
{
public static string ActionLink(this HtmlHelper htmlHelper, string linkText, string actionName, string controllerName, bool requireAbsoluteUrl)
{
return htmlHelper.ActionLink(linkText, actionName, controllerName, new RouteValueDictionary(), new RouteValueDictionary(), requireAbsoluteUrl);
}
// more of these
public class DomainRoute : Route
{
//
![](https://www.cnblogs.com/Images/dot.gif)
public string Domain { get; set; }
//
![](https://www.cnblogs.com/Images/dot.gif)
public override RouteData GetRouteData(HttpContextBase httpContext)
{
// 构造regex
domainRegex = CreateRegex(Domain);
pathRegex = CreateRegex(Url);
// 请求信息
string requestDomain = httpContext.Request.Headers["host"];
if (!string.IsNullOrEmpty(requestDomain))
{
if (requestDomain.IndexOf(":") > 0)
{
requestDomain = requestDomain.Substring(0, requestDomain.IndexOf(":"));
}
}
else
{
requestDomain = httpContext.Request.Url.Host;
}
string requestPath = httpContext.Request.AppRelativeCurrentExecutionFilePath.Substring(2) + httpContext.Request.PathInfo;
//匹配域名和路由
Match domainMatch = domainRegex.Match(requestDomain);
Match pathMatch = pathRegex.Match(requestPath);
// Route 数据
RouteData data = null;
if (domainMatch.Success && pathMatch.Success)
{
data = new RouteData(this, RouteHandler);
// 添加默认选项
if (Defaults != null)
{
foreach (KeyValuePair<string, object> item in Defaults)
{
data.Values[item.Key] = item.Value;
}
}
// 匹配域名路由
for (int i = 1; i < domainMatch.Groups.Count; i++)
{
Group group = domainMatch.Groups[i];
if (group.Success)
{
string key = domainRegex.GroupNameFromNumber(i);
if (!string.IsNullOrEmpty(key) && !char.IsNumber(key, 0))
{
if (!string.IsNullOrEmpty(group.Value))
{
data.Values[key] = group.Value;
}
}
}
}
// 匹配域名路径
for (int i = 1; i < pathMatch.Groups.Count; i++)
{
Group group = pathMatch.Groups[i];
if (group.Success)
{
string key = pathRegex.GroupNameFromNumber(i);
if (!string.IsNullOrEmpty(key) && !char.IsNumber(key, 0))
{
if (!string.IsNullOrEmpty(group.Value))
{
data.Values[key] = group.Value;
}
}
}
}
}
return data;
}
public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary values)
{
return base.GetVirtualPath(requestContext, RemoveDomainTokens(values));
}
public DomainData GetDomainData(RequestContext requestContext, RouteValueDictionary values)
{
// 获得主机名
string hostname = Domain;
foreach (KeyValuePair<string, object> pair in values)
{
hostname = hostname.Replace("{" + pair.Key + "}", pair.Value.ToString());
}
// Return 域名数据
return new DomainData
{
Protocol = "http",
HostName = hostname,
Fragment = ""
};
}
//
![](https://www.cnblogs.com/Images/dot.gif)
}
哇,这是一串按照我们定义的route转换传入请求的URL到tokens的代码,我们这样做是转换{controller}和按照regex然后再尝试匹配route规则,在我们的DomainRoute class里还有其他的helper方法,需要更多的功能可以自己研究扩展。
附代码:附件
相关文章推荐
- asp.net form 验证方式的使用(转载)
- asp.net下通过泛解析和伪静态实现二级域名的实现方法
- ASP.NET MVC AJAX的调用示例
- ASP.NET Session 详解
- WebForm页面生命周期及asp.net运行机制
- .NET/ASP.NET Routing路由(深入解析路由系统架构原理)
- ASP 连接Access2013的accdb文件
- spring AspectJ的Execution表达式-备忘札记
- JDK8:PermGen变更为MetaSpace详解
- ASPNET常用工具方法(二)
- 利用ASP.NET MVC+Bootstrap搭建个人博客之打造清新分页Helper(三)
- [转]asp.net c# 网上搜集面试题目(附答案)
- 利用ASP.NET MVC+Bootstrap搭建个人博客之praise.js点赞特效插件(二)
- aspnet常用工具方法(一)
- 利用ASP.NET MVC和Bootstrap快速搭建响应式个人博客站(一)
- ASPNET的网站静态化URL重写
- ASP.Net 对xml文件的读写,添加,修改,删除操作
- ASP.Net中,如何自动保存文件到指定位置
- 利用Aspose.Word控件和Aspose.Cell控件,实现Word文档和Excel文档的模板化导出
- 利用ASP.NET MVC和Bootstrap快速搭建响应式个人博客站(一)