2014-11-08 6 views
1

MVC 4를 사용하고 방문 페이지에 문제가 있습니다.
Foo/Index와의 사용자가 로그인 한 번 Bar/Index
, 나는 그가 푸 또는 바인지를 식별하고 :
나는 사용자 (의가 FooUserBarUser를 부르 자)
사용자의 각이가 자신의 방문 페이지의 두 가지 종류가있다 해당 페이지로 리디렉션하십시오.
하지만 여전히 문제가 있으며 사용자가 기본 페이지를 열 때입니다. 이 경우 사용자는 이전 세션에서 로그인 했으므로 로그인 작업을 수행하지 않으므로 관련 페이지로 리디렉션 할 수 없습니다.
조건부 기본값을 설정하는 방법이 있습니까? 뭔가 같은 :
당신이 정말로 다른 사용자를위한 새로운 컨트롤러를 필요로하는 경우 그것은 고려 가치가있을 수도 있습니다MVC 4와 다른 방문 페이지

if (IsCurrentUserFooUser()) //Have no idea how to get the current user at this point in the code 
{ 
    routes.MapRoute(
     name: "Default", 
     url: "{controller}/{action}/{id}", 
     defaults: new { controller = "Foo", action = "Index", id = UrlParameter.Optional }); 
} 
else 
{ 
    routes.MapRoute(
     name: "Default", 
     url: "{controller}/{action}/{id}", 
     defaults: new { controller = "Bar", action = "Index", id = UrlParameter.Optional }); 
} 

답변

2

(다른 아이디어가 가장 환영합니다). 왜 그냥 다른보기를 반환하고 컨트롤러에서 일부 논리를하지. 이것은 내가 선호하는 경로 일 것이므로 오버 헤드가 적어서 동적으로 경로를 계산할 수 있습니다.

경로는 응용 프로그램이 시작될 때 매핑되므로 조건부 경로를 수행 할 수 없습니다. 요청 당 처리되는 동적 경로를 사용할 수 있으므로 일부 논리를 통해 해당 경로가 일치하는지 확인할 수 있습니다.

참고 : return null은 동적 경로의 어느 지점에서나이를 취소하고 해당 요청에 대해 유효하지 않게 만듭니다.

public class UserRoute: Route 
{ 
    public UserRoute() 
     : base("{controller}/{action}/{id}", new MvcRouteHandler()) 
    { 
    } 

    public override RouteData GetRouteData(HttpContextBase httpContext) 
    { 
     var rd = base.GetRouteData(httpContext); 
     if (rd == null) 
     { 
      return null; 
     } 

     //You have access to HttpContext here as it's part of the request 
     //so this should be possible using whatever you need to auth the user. 
     //I.e session etc. 
     if (httpContext.Current.Session["someSession"] == "something") 
     { 
      rd.Values["controller"] = "Foo"; //Controller for this user 
      rd.Values["action"] = "Index"; 
     } 
     else 
     { 
      rd.Values["controller"] = "Bar"; //Controller for a different user. 
      rd.Values["action"] = "Index"; 
     } 

     rd.Values["id"] = rd.Values["id"]; //Pass the Id that came with the request. 

     return rd; 
    } 
} 

는 다음과 같이 사용될 수있다 :

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

    routes.Add("UserRoute", new UserRoute()); 

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