There are two ways, the first and the most viable is
Validate the session through a FilterAttribute
Only make use of the annotation [Authorize]
1. Using a FilterAttribute
You can implement a FilterAttribute
where you can validate if the user is authenticated. First you must create a class ValidateAuthenticationFilterAttribute
that inherits from ActionFilterAttribute
, and if the user has not been authenticated, a redirection must be made to the permission page denied (assuming that your Controller is called Permissions and the Action is Denied):
public class ValidateAuthenticationFilterAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (/*Aquí validas si el usuario tiene los permisos*/)
{
filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new { controller = "Permisos", action = "Denegado" }));
}
base.OnActionExecuting(filterContext);
}
}
Finally, in the Controler sol you will have to put the annotation [ValidateAuthenticationFilter]
:
[ValidateAuthenticationFilter]
public class UnidadesController : Controller
{
//TO DO
}
2. Using the annotation [Authorize]
If the user is not logged in the system and this annotation is used, the application will redirect to Controller and Action declared by default in the App_Start \ RouteConfig.cs file:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Login", action = "Index", id = UrlParameter.Optional }
);
}
Your code would be as follows:
[Authorize]
public class UnidadesController : Controller
{
//TO DO
}