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 cookies (ex UserID) once the user log's in.. and all I want to do is create an attribute where if the
if (Session["UserID"] == null)
then it will redirect to login just like the [Authorize] attribute does. That way I can apply this attribute on the Controller level everywhere.
Should I overwrite the Authorize attribute? Create a new one? How do I get it to redirect to login as well?
I'm also using ASP.NET MVC 4
Thanks for any help
Best Solution
You can create a custom
AuthorizeAttribute
and overrideAuthorizeCore()
andHandleUnauthorizedRequest()
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)Do not forget to set the
Session["UserID"]
variable in your/User/Login
action method after proper user validation.