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

.netasp.netasp.net-mvcasp.net-mvc-4c++

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 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.