asp.net MVC中的URLRewriting

时间:2014-09-24 11:39:05

标签: asp.net-mvc

我需要在我的网站中注册新用户时在网站中创建一个子域名。该用户名将在网站中用作子域名 这可以通过asp.net MVC中的URLRewriting来实现。任何人都有任何想法请告诉我 “一个示例项目将是一个加分点”

1 个答案:

答案 0 :(得分:0)

您不需要在MVC中使用URLRewriting,您可以扩展框架的现有路由功能。以下是从the asp.net forums获取的代码示例:

public class SubdomainRoute : Route
{
    public SubdomainRoute(string url) : base(url, new MvcRouteHandler()) {}

    public override RouteData GetRouteData(HttpContextBase httpContext)
    {
        var routeData = base.GetRouteData(httpContext);
        if (routeData == null) return null; // Only look at the subdomain if this route matches in the first place.
        string subdomain = httpContext.Request.Params["subdomain"]; // A subdomain specified as a query parameter takes precedence over the hostname.
        if (subdomain == null) {
            string host = httpContext.Request.Headers["Host"];
            int index = host.IndexOf('.');
            if (index >= 0)
                subdomain = host.Substring(0, index);
        }
        if (subdomain != null)
            routeData.Values["subdomain"] = subdomain;
        return routeData;
    }

    public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary values)
    {
        object subdomainParam = requestContext.HttpContext.Request.Params["subdomain"];
        if (subdomainParam != null)
            values["subdomain"] = subdomainParam;
        return base.GetVirtualPath(requestContext, values);
    }
}

您还可以为RouteCollection创建一个扩展方法,以便更轻松地映射子域路由。