Session Authorization And Expire In Asp.Net MVC
Today, I want to talk about Session operations in Asp.net Mvc Projects. Every web projects needs a login page and authorization. When user logins the page, we want user to be logged again to the project if session time is up. Let start it from Session Authorization.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Routing; namespace CodingFaster.App_Start { public class SessionAuthorizeAttribute : AuthorizeAttribute { protected override bool AuthorizeCore(HttpContextBase httpContext) { return httpContext.Session["User"] != null; } protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext) { filterContext.Result = new RedirectToRouteResult( new RouteValueDictionary { { "area"," "}, { "action", "Login" }, { "controller", "Login"} }); } } } |
We must add this attribute in order to provide session authorization in our project. Secondly, we will add Session Expire attribute to our project. This is for session time out operations.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace CodingFaster.App_Start { public class SessionExpireAttribute : ActionFilterAttribute { public override void OnActionExecuting(ActionExecutingContext filterContext) { HttpContext ctx = HttpContext.Current; if (ctx.Session["User"] == null) { filterContext.Result = new RedirectResult("~/Login/Login"); return; } base.OnActionExecuting(filterContext); } } } |
In this code, we will redirect the user to the login page if session time out happens. At the same time, we will add this filters to our controllers by annotations.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
using System; using System.Collections.Generic; using System.Linq; using System.Web.Mvc; using System.Linq.Dynamic; using System.Web.UI; namespace CodingFaster.Controllers { [SessionAuthorize, SessionExpire] public class TaskController : Controller { public ActionResult Index() { return View(); } } |
You should have a look at my another post about Logging In Asp.Net MVC
If you have question do not forget to write from the chat button next to it or from the comment.
I know this if off topic but I’m looking into starting my own weblog
and was curious what all is required to get setup? I’m assuming having a
blog like yours would cost a pretty penny?
I’m not very internet smart so I’m not 100% certain. Any
recommendations or advice would be greatly appreciated. Kudos