2016-07-27 188 views
0

因此,我的新網站應用程序,是動態網頁和基於子域的作品。 即http://company1234.domain.com 然後,我採取參數「company1234」並做一個web api調用來獲取頁面信息顯示。ASP.NET MVC路由 - 子域名

這一切工作得很好。 但是我的問題是,如果我需要調用一個參數的URL即http://company1234.domain.com/Home/GetClient?id=abcdhttp://company1234.domain.com/Home/GetClientAccountDetails?model=abcd&acc=1234

我所有的路由被破壞,無法弄清楚如何我返工呢?

public class SubdomainRoute : RouteBase 
     { 
      public override RouteData GetRouteData(HttpContextBase httpContext) 
      { 
       if (httpContext.Request == null || httpContext.Request.Url == null) 
       { 
        return null; 
       } 

       var host = httpContext.Request.Url.Host; 
       var index = host.IndexOf("."); 

       string[] segments = httpContext.Request.Url.PathAndQuery.TrimStart('/').Split('/'); 

       if (index < 0) 
       { 
        return null; 
       } 

       var subdomain = host.Substring(0, index); 

       string controller = (segments.Length > 0) ? segments[0] : "Home"; 
       string action = (segments.Length > 1) ? segments[1] : "Index"; 


       var routeData = new RouteData(this, new MvcRouteHandler()); 
       routeData.Values.Add("controller", "Home"); 
       routeData.Values.Add("action", action); 
       routeData.Values.Add("subdomain", subdomain); 



      return routeData; 
      } 

      public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary values) 
      { 
       //Implement your formating Url formating here 
       return null; 
      } 
     } 

我的控制器方法

public ActionResult Index(string subdomain) 
     { 
//Go get custom page info 
      var profile = GetProfile(subdomain); 



      return View("Default", profile); 
     } 

public JsonResult GetClient(string id) 
     { 

//do stuff 
} 

我的全球

public static void RegisterRoutes(RouteCollection routes) 
     { 
      routes.Add(new SubdomainRoute()); 

      routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); 
      routes.IgnoreRoute("favicon.ico"); 
      routes.MapRoute("Home", 
          "", 
          new { controller = "Application", action = "Login" }); 
      routes.MapRoute(
       "Default", // Route name 
       "{controller}/{action}/{id}", // URL with parameters 
       new {controller = "Home", action = "Index", id = UrlParameter.Optional}); 
     } 

如果我打電話 http://company1234.domain.com/Home/GetClient

那麼這種方法被擊中,但如果我叫 http://company1234.domain.com/Home/GetClient?id=1234 它不起作用

任何想法,我需要做的,以重新工作,並得到它的工作?

回答

0

路線需要做兩件事情:

  1. 確定它們是否符合要求。
  2. 如果他們這樣做,返回一組路由值。

要處理第一個要求,必須將路線返回null,如果它不匹配傳入的請求。這告訴路由框架檢查路由表中的下一個註冊路由。

問題是你的路由不檢查以確保傳遞的URL是它應該處理的東西,因此它總是匹配請求,並且因爲它在所有其他路由之前被註冊,所以沒有其他路由可以被達到。通常情況下,檢查httpContext.Request.Path以確保它符合某些標準,如果不符合,則應返回null