3

我正在寻找一种将通配符子域路由到 ASP MVC 4 中的控制器的方法。

所以是这样的:

公司名称.mydomain.com

需要翻译成这样:

mydomain.com/CompanyName

我找不到有关如何执行此操作的任何信息,我被卡住了。这是 IIS 的事情还是 ASP MVC 路由的事情?

4

3 回答 3

5

因此,经过相当长的一段时间后,我自己在应用程序级别解决了这个问题。IIS 重写不起作用,ASP MVC 没有匹配正确的路由,它会出现 404 错误。

最终对我有用的解决方案是制作我自己的路由类实现,它在主机名中搜索参数并将其映射为路由参数。它现在可以完美运行,并且自定义实现很简单。我爱上了 ASP MVC 在此过程中为您提供的灵活性 :)

因此,自定义路由需要两个覆盖,一个用于匹配传入路由的“GetRouteData”方法,第二个用于写入传出路由的“GetVirtualPath”。

这是整个自定义路由类:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace System.Web.Routing
{
public class WildcardRoute : Route
{


    public WildcardRoute(string url, IRouteHandler handler)
        : base(url, handler)
    { 

    }
    public WildcardRoute(string url, RouteValueDictionary defaults, IRouteHandler handler)
        : base(url, defaults, handler)
    {
    }

    public WildcardRoute(string url, RouteValueDictionary defaults, RouteValueDictionary constraints, IRouteHandler handler)
        : base(url, defaults, constraints, handler)
    { 
    }

    public WildcardRoute(string url, RouteValueDictionary defaults, RouteValueDictionary constraints, RouteValueDictionary dataTokens, IRouteHandler handler)
        : base(url, defaults, constraints, dataTokens, handler)
    {

    }


    public override RouteData GetRouteData(HttpContextBase httpContext)
    {
        // save the original path before we edit it
        var orignalPath = HttpContext.Current.Request.Path;

        //split the hostname
        var split = HttpContext.Current.Request.Url.Host.Split('.');
        // fire only if there is more than 2 items in the split (company.mydomain.com) and if the first one is not www
        if (split.Count() > 2 && split[0].ToLower() != "www")
        {
            var split2 = HttpContext.Current.Request.Path.Split('/'); // split everything  after the hostname into segments
            string newPath = "/" + split[0]; // take the company from company.mydomain.com and rewrite it to mydomain.com/company
            foreach (var item in split2) // add all the other segments that come after mydomain.com/company 
            {                            // end result might be for example - mydomain.com/company/Home/Index 
                newPath = newPath + "/" + item;
            }
            httpContext.RewritePath(newPath); // rewrite the path into the newone
        }

        RouteData data = base.GetRouteData(httpContext); // match the route with the new path
        if (data == null) // if there is no match in this route write the path back to the original one
        {
            httpContext.RewritePath(orignalPath);
        }
        return data;
    }

    public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary values)
    {

        var data = base.GetVirtualPath(requestContext, values); // do the original url write
        var split = requestContext.HttpContext.Request.Url.Host.Split('.'); // split the host by '.'

        var item = requestContext.RouteData.Values.FirstOrDefault(x => x.Key == "PermalinkTitle"); // the PermalinkTitle is the name of the "company" route value in mydomain.com/company in my implementation
        if (split.Count() > 0 && split[0].ToLower().Contains(item.Value.ToString().ToLower())) // fire only if the hostname contains the "company" route value
        {
            data.VirtualPath = data.VirtualPath.Replace(item.Value.ToString(), "");
            if (data.VirtualPath.StartsWith("/"))
                data.VirtualPath = data.VirtualPath.Substring(1);
            // this code removes the company part from the path so we dont get company.mydomain.com/company/controller/action rather we just get company.mydomain.com/controller/action
        }
        return data;
    }

}
}

这个实现足够灵活,可以与所有这些路由一起工作——“company.mydomain.com”、“mydomain.com/company”和“www.mydomain.com/company”。

制作自定义路由类后,您需要使用映射自定义类型路由的 Map 方法扩展 RouteCollection,如果使用 Areas,还需要扩展 AreaRegistrationContext,因为区域路由映射会通过该方法。这是整个实现:

using System;
using System.Web.Mvc;
using System.Web.Routing;

namespace System.Web.Routing
{
    public static class WildcardRoutesExtension
    {

        public static WildcardRoute MapWildcardRoute(this RouteCollection routes, string name, string url, object defaults)
        {

            WildcardRoute route = new WildcardRoute(
                url,
                new RouteValueDictionary(defaults),
                new MvcRouteHandler());
            routes.Add(name, route);

            return route;
        }

        public static WildcardRoute MapWildcardRoute(this AreaRegistrationContext context, string name, string url, object defaults)
        {
                        WildcardRoute route = new WildcardRoute(
                url,
                new RouteValueDictionary(defaults),
                new RouteValueDictionary(new {}),
                new RouteValueDictionary(new {Area = context.AreaName }),
                new MvcRouteHandler());

            context.Routes.Add(name, route);
            return route;
        }


        public static WildcardRoute MapWildcardRoute(this AreaRegistrationContext context, string name, string url, object defaults, object constraints)
        {
            WildcardRoute route = new WildcardRoute(
                url,
                new RouteValueDictionary(defaults),
                new RouteValueDictionary(constraints),
                new RouteValueDictionary(new {Area = context.AreaName }),
                new MvcRouteHandler());

            context.Routes.Add(name, route);
            return route; 
        }

        public static WildcardRoute MapWildcardRoute(this RouteCollection routes, string name, string url, object defaults, object constraints)
        {
            WildcardRoute route = new WildcardRoute(
                url,
                new RouteValueDictionary(defaults),
                new RouteValueDictionary(constraints),

                new MvcRouteHandler());
            routes.Add(name, route);
            return route;
        }
    }
}

当您拥有所有这些后,您现在只需要像这样为 RouteConfig 类中的常规路由映射您的自定义路由:

    public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {


                 // rest of your routes

                routes.MapWildcardRoute(
                          name: "Default",
                          url: "{PermalinkTitle}/{controller}/{action}",
                          defaults: new {  }
                 );

              //Rest of your routes
        } 

或者对于 Areas AreaRegistration 类中的区域是这样的:

    public override void RegisterArea(AreaRegistrationContext context)
    {

        context.MapWildcardRoute(
            "MyArea_default",
            "{PermalinkTitle}/MyArea/{controller}/{action}/{id}",
            new { action = "Index", id = UrlParameter.Optional }
        );

    }
于 2013-10-08T16:57:22.573 回答
0

尝试将此规则用于 IIS:

<rule name="Rule1" stopProcessing="true">
    <match url=".*" />
    <conditions>
        <add input="{HTTP_HOST}" pattern="^(?!www)(.*)\.mydomain\.com$" />
    </conditions>
    <action type="Rewrite" url="http://mydomain.com/{C:1}/{R:0}" />
</rule> 
于 2013-06-30T16:47:14.763 回答
0

我会说这主要与两者有关。在大多数情况下,子域实际上是域服务器上根目录之外的文件夹。(即,CompanyName.mydomain.com 通常是 mydomain.com/CompanyName 文件夹(就像您编写的那样))。

然后,由你的 mvc 路由来设置你想要的路由。使用 mvc 路由,我使用这个方向:控制器/动作。

IIS 会将您作为子域的根目录转换为您的 CompanyName 文件夹。您的 mvc 只需要在该文件夹的控制器文件夹内有一个主控制器即可使用您的任一 url 定义导航到那里。

于 2013-06-30T16:47:37.327 回答