Create Actionfilter for "Anonymous" login

Asked

Viewed 51 times

0

I looked it up online, but I couldn’t find the answer to what I wanted. I have the simple code below that checks if 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 in the same Controller that I didn’t want you to perform this check whether you’re logged in or not. So I just created this other Actionfilter where it does nothing and put it on top of the controller method that I don’t want you to check whether or not you are logged in:

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

    }
}

But it’s not working, it still keeps coming back to the Login screen and that’s not what I want to happen. What should I put in Filtroanonimo so that it ignores the function of Filtrologin?

  • I see no use in all this. Request.IsAuthenticated + [Authorize] Already solve it for you.

  • Yeah, I saw about this guy. But what if one day I need to create my own custom filter but in some methods I don’t need to use it in some method in the same controller?

  • Like I said, Request.IsAuthenticated + [Authorize]. No need to reinvent the wheel.

1 answer

2

The simple decoration of [Authorize] in their 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) { ... }
    }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.