Perform a redirect on Builder

2

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

public class FarmaciaController : Controller{

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

}
    
asked by anonymous 09.06.2015 / 18:38

1 answer

4

Redirecting in the constructor may give some problems because of the context as well as not being a good practice, one solution is to create a custom attribute for your action and override the OnActionExecuting method to do the validation.

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 on your Controller

public class FarmaciaController : Controller
{
    [ValidarPermissaoAction]
    public ActionResult Index()
    {
        // Essa action só vai ser executada se a validação tiver ok
        return View();
    }
}
    
09.06.2015 / 18:55