2011-08-09 22 views
1

我在想如何正確安全JsonResult動作與自定義屬性而不是做那種這對每個動作就像在說這裏ASP.NET MVC JsonResult and AuthorizeAttribute如何創建自定義的JsonAuthorize屬性來保護返回JsonResults的操作?

if (!User.Identity.IsAuthenticated) 
    return Json("Need to login"); 

但問題是我怎麼能創造這樣的屬性,它會返回JSON。 所以我從開始:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)] 
    public class JsonAuthorizeAttribute : AuthorizeAttribute 
    { 
     protected override bool AuthorizeCore(HttpContextBase httpContext) 
     { 
      if (httpContext == null) 
      { 
       throw new ArgumentNullException("httpContext"); 
      } 
      IPrincipal user = httpContext.User; 

      if (!user.Identity.IsAuthenticated) 
      { 
       //? 
      } 

      //Need to return json somehow ? 
     } 
    } 

博特如何我可以從這樣的屬性返回JSON結果?有任何想法嗎?

回答

3

您可以使用一個ActionFilterAttribute它允許您返回一個結果,而不使用httpcontext.response.write或任何東西。

public class JsonActionFilterAttribute : ActionFilterAttribute { 
    public override void OnActionExecuting(ActionExecutingContext filterContext) { 
     if (!HttpContext.Current.User.Identity.IsAuthenticated) { 
      filterContext.Result = new JsonResult() { Data = "Need to login." }; 
     } 
     base.OnActionExecuting(filterContext); 
    } 
} 
3

1方法是重寫AuthorizeAttribute.HandleUnauthorizedRequest

protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext) 
{ 
    throw new CustomUnauthorizedException(); 
} 

...然後在您的Global.asax:

protected void Application_Error(object sender, EventArgs e) 
{ 
    Exception error = Server.GetLastError(); 
    if (error is CustomUnauthorizedException) { 
     if (AjaxRequest(Request)) { 
      ... return Json response. 
     } else { 
      ... redirect 
     } 
    } 
} 

所以,你可以在任何地方拋出異常的代碼庫並且您已將該異常的處理集中在Global.asax

相關問題