0

I am currently building a user login system in MVC 5 for practice. What I wanna do is, making a controller only accessable if you have the session "UserId".

Surely, I could just make an if statement in every action, like this:

public ActionResult Index()
{
    if (Session["UserId"] != null)
    {
        return View();
    }
    else
    {
        return RedirectToRoute("Home");
    }
}

But is there a way I can make that happen with all the actions in the controller?

Bonus info: I have 2 controllers - HomeController - AccountController

2
  • see: stackoverflow.com/questions/24970955/… Commented Aug 8, 2014 at 14:13
  • 1
    As long as it's "for practice" I suppose that's fine, though I think there's far better things you could practice. In the end, don't try to roll your own authentication system for real. As your approach here bears out, it's harder than you think to do right. Commented Aug 8, 2014 at 14:53

2 Answers 2

2

You would implement an authorize filter and apply that filter to your controller. Something like this:

public class CustomAuthenticationAttribute : ActionFilterAttribute, IAuthenticationFilter
{
    public void OnAuthentication(AuthenticationContext filterContext)
    {            
    }

    public void OnAuthenticationChallenge(AuthenticationChallengeContext filterContext)
    {            
        if (filterContext.HttpContext.Session["UserId"] == null)
        {
            filterContext.Result = new HttpUnauthorizedResult();
        }
    }
}

Then you could apply the [CustomAuthentication] attribute to your controller directly, or you can do it by each action in your controller. Something like this:

[CustomAuthentication]//<-- If you put it here, it applies to the whole controller
public class HomeController : Controller
{
    [CustomAuthentication]//<-- Here it only applies to the Index action
    public ActionResult Index()
    {
        return View();
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

I believe what you are looking for is a custom ActionFilter. Code in an ActionFilter can be executed before the ActionResult, allowing you to redirect anyone without the UserId session.

Instead of putting code in every ActionResult you would do something like this

[MyCustomActionFilter]
public ActionResult Index()
{
    return View();
}

Here is a tutorial on how to create one Custom Action filters in MVC

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.