2015-02-06 25 views
0

我正在尋找一些關於如何實現以下內容的建議。如何根據主機名加載正確的控制器

我有一個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。 uk/controller1/Index
我正在做的另一件事是使用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

您可以實現驗證主機名

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」中所示)

+0

Brillant :)非常感謝你 – 2015-02-06 16:30:52

相關問題