2010-03-18 2 views
50

ASP.Net MVC 2를 사용하여 AuthorizeAttribute 클래스를 기반으로하는 클래스 내에 Controller 클래스의 RedirectToAction() 메서드를 사용할 수 있습니까?커스텀 AuthorizeAttribute 클래스에서 RedirectToAction()을 사용할 수 있습니까?

public class CustomAttribute : AuthorizeAttribute { 
    protected override bool AuthorizeCore(HttpContextBase context) { 
     // Custom authentication goes here 
     return false; 
    } 

    public override void OnAuthorization(AuthorizationContext context) { 
     base.OnAuthorization(context); 

     // This would be my ideal result 
     context.Result = RedirectToAction("Action", "Controller"); 
    } 
} 

나는 다시 직접 할 수있는 사용자를 특정 컨트롤러/액션에 그들은 로그인 페이지로 반환하는 대신 인증에 실패 할 때 방법을 찾고 있어요. 해당 컨트롤러/작업에 대해 리디렉트 URL을 생성 한 다음 RedirectResult()을 사용할 수 있습니까? URL을 하드 코딩하려는 유혹을 피하려고합니다.

답변

94

OnAuthorization 대신 HandleUnauthorizedRequest을 무시할 수 있습니다. 여기에 기본 구현의 :

protected virtual void HandleUnauthorizedRequest(AuthorizationContext filterContext) { 
     // Returns HTTP 401 - see comment in HttpUnauthorizedResult.cs. 
     filterContext.Result = new HttpUnauthorizedResult(); 
    } 

당신은 Controller.RedirectToAction를 사용할 수 없지만 새로운 RedirectToRouteResult을 반환 할 수 있습니다.

그래서 당신은 할 수 있습니다 경우 다른 사람에

protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext) { 
     // Returns HTTP 401 - see comment in HttpUnauthorizedResult.cs. 
     filterContext.Result = new RedirectToRouteResult(
            new RouteValueDictionary 
            { 
             { "action", "ActionName" }, 
             { "controller", "ControllerName" } 
            }); 
    } 
+1

고마워, 그거야. HandleUnauthorizedRequest 사용에 대한 좋은 이해 - 다른 튜토리얼/토론에서 본 OnAuthorization을 사용하고있었습니다. 인증에 실패하면 설정된 리다이렉트를 트리거 할 사용자 정의 속성이 있습니다. –

+0

@ LanceMcNearney filterContext 매개 변수에서 무엇을 전달하겠습니까? – Pomster

+0

@Craig Stuntz filterContext로 무엇을 전달하겠습니까? – Pomster

11

당신은 같은 것을 할 수 있습니다

var routeValues = new RouteValueDictionary(); 
routeValues["controller"] = "ControllerName"; 
routeValues["action"] = "ActionName"; 
//Other route values if needed. 
context.Result = new RedirectToRouteResult(routeValues); 

이것은 당신이 당신의 컨트롤러에서 "RedirectToAction()"를 호출 할 때 프레임 워크가 그것을 수행하는 방법이다.

+0

컨텍스트 란 무엇입니까? 내가 빨간색 밑줄을 그렸어? – Pomster

+0

@Pomster 질문을 확인하십시오. "컨텍스트"는 질문에 관한 메서드의 매개 변수입니다. –

+0

감사합니다.이 작품을 제작하려면 무엇이 전달되어야합니까? 이 작업을 수행하는 데 어려움을 겪고 있습니다. – Pomster

2

이 문제에 관심을 가지고있다.

그냥 사용자 정의 AuthorizeAttribute에있는 작은 개인 컨트롤러 생성 : 이 (MVC 3 사용 적어도, MVC 2 모르는) 간단한 방법으로 해결 될 수

private class RedirectController : Controller 
    { 
     public ActionResult RedirectWhereever() 
     { 
      return RedirectToAction("Action", "Controller"); 
     } 

    } 

을이 작업을 쉽게 할 수 있습니다 HandleUnauthorizedRequest 메소드에서 사용하십시오 (Craigs 응답 참조).

filterContext.Result = (new RedirectController()).RedirectWhereever(); 
+2

'RedirectToAction'은'RedirectToRouteResult'를 반환합니다. @Craig Stuntz가 대답 했으므로 컨트롤러를 생성하기 위해 컨트롤러를 만들 필요가 없습니다. –

관련 문제