如何根据主机名加载正确的控制器

时间:2015-02-06 14:43:11

标签: asp.net-mvc-5 ninject.web.mvc

我正在寻找有关如何实现以下目标的一些建议。

我有一个MVC5 .NET Web应用程序。在这个应用程序中,我创建了一个基本控制器,该控制器是许多子控制器的父控制器。每个子控制器都有自己的一组视图,这些视图有自己的sass和JavaScript文件集。我需要做的是根据主机URL加载正确的控制器,而不是在URL中显示控制器名称,例如www.host1.co.uk将加载controller1和www.host2.co.uk将加载controller2,当网站运行时,URL需要看起来像这样www.host1.co.uk/Index NOT www.host1.co。英国/控制器1 /指数
我正在做的另一件事是使用Ninject将所有业务逻辑服务注入控制器,我想继续这样做。

任何帮助将不胜感激

以下是参考

的控制器结构示例
public abstract class BaseController : Controller
    {
        private readonly IService1 _service1;
        private readonly IService2 _service2;

        protected BaseController(IService1 service1, IService2 service2)
        {
            _service1 = service1;
            _service2 = service2;
        }

        // GET: Base
        public virtual ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public virtual ActionResult Index(IndexViewModel model)
        {
            //DoSomething
            return View();

        }
    }


    public class HostController1 : BaseController
    {
        public HostController1(IService1 service1, IService2 service2)
            : base(service1, service2)
        {

        }
    }

1 个答案:

答案 0 :(得分:1)

您可以实现验证主机名的自定义路由约束

namespace Infrastructure.CustomRouteConstraint
{
    public class HostNameConstraint : IRouteConstraint
    {
        private string requiredHostName;

        public HostNameConstraint(string hostName)
        {
            requiredHostName = hostName;
        }

        public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
        {
            // get the host name from Url.Authority property and compares it with the one obtained from the route
            return httpContext.Request.Url.Authority.Contains(requiredHostName);
        }
    }
}

然后,在RouteConfig.cs的顶部,您可以创建两个指定这些主机名的新路由:

public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute("Host1Route", "{action}",
                new { controller = "One", action = "Index" },
                new { customConstraint = new HostNameConstraint("www.host1.co.uk") });

            routes.MapRoute("Host2Route", "{action}",
                new { controller = "Two", action = "Index" },
                new { customConstraint = new HostNameConstraint("www.host2.co.uk") });

            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );
        }

现在,来自主机“www.host1.co.uk”的每个请求都将使用“OneController”的操作方法处理,来自“www.host2.co.uk”的每个请求都将通过以下操作方法处理: “TwoController”(并且URL中没有控制器名称,如“www.host2.co.uk/Test”)