How to create a custom attribute that will redirect to Login if it returns false, similar to the Authorize attribute - ASP.NET MVC

前端 未结 2 764
后悔当初
后悔当初 2020-12-15 23:45

I tried Googling a few things about custom attributes but I\'m still not sure how to go about it....

I\'m storing a few important details of the user in Session cook

相关标签:
2条回答
  • 2020-12-16 00:16

    You can create a custom AuthorizeAttribute and override AuthorizeCore() and HandleUnauthorizedRequest() as required. Add your own logic which will do the check and redirect if necessary.

    I'm just showing a simple example using MVC's ActionFilterAttribute (which is not the best place to do authentication/authorization)

    public class VerifyUserAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var user = filterContext.HttpContext.Session["UserID"];
            if (user == null)
                filterContext.Result = new RedirectResult(string.Format("/User/Login?targetUrl={0}",filterContext.HttpContext.Request.Url.AbsolutePath));
        }
    }
    

    Do not forget to set the Session["UserID"] variable in your /User/Login action method after proper user validation.

    0 讨论(0)
  • 2020-12-16 00:17

    You can create your own version of the Authorize attribute by implementing the IAuthorizationFilter interface. Here's an example:

    class MyCustomFilter : FilterAttribute, IAuthorizationFilter
    {
        public void OnAuthorization(AuthorizationContext filterContext)
        {
            if (filterContext.HttpContext.Session["UserID"] == null)
            {
                filterContext.Result = new RedirectResult("/");
            }
        }
    }
    

    and a usage example:

    [MyCustomFilter]
    public ActionResult About()
    {
        ViewBag.Message = "Your application description page.";
    
        return View();
    }
    
    0 讨论(0)
提交回复
热议问题