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

前端 未结 2 765
后悔当初
后悔当初 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: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();
    }
    

提交回复
热议问题