0

In my application I am restricting some view and the user has to be logged in to view them. One way would be to check on every action if the user is logged in or not. But after a bit of research I found that asp.net MVS supports some global filter rules.

How do we use them? Ideally I would want to call a filter onBeforeAction and check if the user is logged in or not..

Is this a right approach? If yes, then can any body give me an example?

2
  • 2
    Add the Authorize attribute to your controller or actions. Commented Dec 1, 2014 at 13:43
  • You will find code examples and detailed explanation here: msdn.microsoft.com/en-us/library/… Commented Dec 1, 2014 at 13:44

2 Answers 2

3

The easiest way is to add the Authorize attribute to your controller or action methods. For example:

public class MyController : Controller
{
    //Normal action
    public ActionResult DoSomethingForAnyone() { }

    //Secured action
    [Authorize]
    public ActionResult DoSomethingOnlyForAuthorisedUsers() { }
}

Alternatively you can secure the entire controller and exclude actions you want to be accessible to anonymous users:

[Authorize]
public class SecureController : Controller
{
    public ActionResult DoSomething() { }

    [AllowAnonymous]
    public ActionResult DoSomethingForAnyone() { }
}
Sign up to request clarification or add additional context in comments.

Comments

0

Your [Authorize] will not work with the custom login. If you are using Form Authentication or other Authentication method than [Authorize] will work smoothly.

For custom login on success set

FormsAuthentication.SetAuthCookie([user name], false);

This will make your [Authorize] attribute to work properly.

And for logout use below statement

FormsAuthentication.SignOut();

If you follow the above solution than it will reduce your code as well as valid user check on before Action call.

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.