Perform a redirect in Constructor

Asked

Viewed 105 times

2

How can I make a Response.Redirect() in a class builder?

public class FarmaciaController : Controller{

    public FarmaciaController(){
        if(!userLogin.usuarioTemPermissao("Farmacia"))
         Response.Redirect("~/PortalFarmacia/Home");
    }  

}

1 answer

4


Redirect in the constructor can give some problems due to context besides not being a good practice, one solution is you create a custom attribute for your action and overwrite the method OnActionExecuting to validate.

public class ValidarPermissaoActionAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        base.OnActionExecuting(filterContext);

        if (/* verificar se o usuario tem permissão */)
        {
            filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new
            {
                controller = "PortalFarmacia",
                action = "Home"
            }));
        }
    }
}

And in his Controller

public class FarmaciaController : Controller
{
    [ValidarPermissaoAction]
    public ActionResult Index()
    {
        // Essa action só vai ser executada se a validação tiver ok
        return View();
    }
}
  • How would I get an attribute from the Class that is calling the validation ? (Pass a parameter)

  • @Danielgregatto If you want to validate the logged in user just take the context, No? What attribute exactly do you need from the class?

  • I am validating permission levels for system controllers, I want to pass a parameter telling the Controller that I am and with this I can validate using my logged in user.

  • 1

    @Danielgregatto You can take the Controller name this way filterContext.ActionDescriptor.ControllerDescriptor.ControllerName

  • That’s what I needed Maicon, thank you! Hug!

Browser other questions tagged

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