I'm looking to create a custom attribute that c开发者_如何学Pythonhecks to see if the user's account has been activated. I need to somehow get the username of the current user. I am using FormsAuthentication.SetAuthCookie()
to login the user.
On any controller method I want to redirect to a particular route if they're not authorized. Can this be done this way? This is how I started.
public class ActivatedAuthroizeAttribute : System.Web.Mvc.AuthorizeAttribute
{
protected override void HandleUnauthorizedRequest(System.Web.Mvc.AuthorizationContext filterContext)
{
// Check to see if user is authorized.
DefaultUnitOfWork unitOfWork = new DefaultUnitOfWork();
//User user = UnitOfWork.UserRepository.IsUserActivated(FormsAuthentication.GetAuthCookie(.Value["Username"]);
base.HandleUnauthorizedRequest(filterContext);
}
I've used the following code to redirect users if they are not authenticated. This is done by overriding the "OnActionExecuting" method to change the controller and action if they are not authenticated. This example shows the redirection to the default mvc login page /Account/LogOn.
public class RequiresAuthenticationAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
//You can put your check here. This particular
//check is for default asp.net membership authentication
if(!filterContext.HttpContext.User.Identity.IsAuthenticated)
{
RedirectToLogin(filterContext);
}
}
private void RedirectToLogin(ActionExecutingContext filterContext)
{
var redirectTarget = new RouteValueDictionary
{
{"action", "LogOn"},
{"controller", "Account"}
};
filterContext.Result = new RedirectToRouteResult(redirectTarget);
}
}
Edit: Obviously then put this attribute at the top of your controller classes, but you knew that... :)
[RequiresAuthentication]
public class HomeController : Controller
{
// code...
}
精彩评论