2013-09-22 3 views
0

ASP.NET MVC4 응용 프로그램이 있습니다. 로그인 페이지를 만들었습니다. 사용자가 시스템에 로그인하면 사용자의 정보를 세션에 등록합니다. 세션 변수를 검사하기위한 필터를 추가했습니다. 사용자가 시스템에 로그인하지 않은 경우 사용자를 내 로그인 컨트롤러로 리디렉션하고 싶습니다.ASP.NET MVC4 ActionFilters

public class SecurityAttribute : ActionFilterAttribute 
    { 
     public override void OnActionExecuting(ActionExecutingContext filterContext) 
     { 
      if (filterContext.HttpContext.Session["User"] == null) 
      { 
       filterContext.HttpContext.Response.RedirectToRoute("Default", new 
       { 
        controller = "Login", 
        action = "DoLogin", 
        returnUrl = filterContext.HttpContext.Request.Url.AbsoluteUri 
       }); 
      } 
      base.OnActionExecuting(filterContext); 
     } 
    } 

컨트롤러 수준에서이 속성을 사용하고 있습니다.

[SecurityAttribute] 
    public class HomeController : Controller 
    { 
     public ActionResult Index() 
     { 
      ViewData["Name"] = ((UserEntity)Session["User"]).Name; 
      ViewData["Surname"] = ((UserEntity)Session["User"]).Surname; 
      return View(); 
     } 
    } 

OnActionExecuting 메서드는 동작을 실행하기 전에 실행되지만 내 홈 컨트롤러에서 동작 메서드 후에 발생하는 동작을 리디렉션합니다. 세션 변수가 null이기 때문에 인덱스 작업에 오류가 발생합니다. 이 문제를 어떻게 해결할 수 있습니까?

답변

2

컨트롤러 동작의 실행을 단락하려면 filterContextResult 속성을 할당해야합니다. 그냥 그렇게 : 또한

public class SecurityAttribute : ActionFilterAttribute 
{ 
    public override void OnActionExecuting(ActionExecutingContext filterContext) 
    { 
     if (filterContext.HttpContext.Session["User"] == null) 
     { 
      var values = new 
      { 
       controller = "Login", 
       action = "DoLogin", 
       returnUrl = filterContext.HttpContext.Request.Url.AbsoluteUri 
      }; 
      var result = new RedirectToRouteResult("Default", new RouteValueDictionary(values)); 

      filterContext.Result = result; 
     } 
    } 
} 

는 그 목적에 대한 권한 부여 필터를 작성하고 오히려 세션 및 물건 바퀴를 개혁보다 내장 된 폼 인증에 의존하는 의미 론적으로 더 정확했을 것이다.

그래서 단순히 :

[Authorize] 
public class HomeController : Controller 
{ 
    public ActionResult Index() 
    { 
     string username = User.Identity.Name; 
     SomeUserModel user = GetUserFromBackend(username); 
     return View(user); 
    } 
} 

당신은 MSDN에서 폼 인증에 대한 자세한 내용을보실 수 있습니다 : http://msdn.microsoft.com/en-us/library/ff647070.aspx