Create ActionFilter for login "Anonymous"

0

I searched the internet but did not find the answer to what I wanted. I have the simple code below that checks whether the user is authenticated or not in my ActionFilter

public class FiltroLogin : ActionFilterAttribute
{
    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
         if (filterContext.HttpContext.Session["Login"] == null)
        {
            filterContext.Controller.TempData["msg"] = "Você precisa realizar o login para acessar esta página";
            filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new { Controller = "Login", Action = "Index" }));
        }
    }
}

But I have a page on the same Controller that did not want me to run this check whether it was logged in or not. So I simply created this other ActionFilter in which it does nothing and put it on top of the controller method that I do not want to check whether it is logged in or not:

public class FiltroAnonimo: ActionFilterAttribute
{
    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {

    }
}

But it is not working, it still keeps coming back to the Login screen being that's not what I want it to happen. What should I put in the FilterAnonimo so that it ignores the function of the FilterLogin?

    
asked by anonymous 29.05.2017 / 00:48

1 answer

2

The simple decoration of [Authorize] in your Controllers and methods already checks whether the user is anonymous or not.

[Authorize]
public class MeuController
{
    ...
}

Or

public class MeuController
{
    [Authorize]
    public ActionResult MinhaAction()
    {
        ...
    }
}

If you need something more specific, you can use Request.IsAuthenticated :

public class MeuController
{
    public ActionResult MinhaAction()
    {
        if (Request.IsAuthenticated) { ... }
    }
}
    
29.05.2017 / 02:12