Pages

Tuesday 18 March 2014

Session management into MVC4

Here I am going to describe you the Session management into the MVC4 application. When user logins the mvc4 application then session will be created for that user and when user logout the session will be get Abandon.

To manage session into mvc4 application create one custom attribute and put the class of that custom attribute into one directory. Here I kept the custom class into the folder named common. Following screenshot describe the same



I given the name CustomAuthentication to the class file and kept that file into common folder.

CustomAuthentication .cs file contains the following code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Routing;
using System.Web.Mvc;

namespace ABC.Web.Common
{
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
    public class CustomAuthorizeAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            try
            {
/*when user login into the system put the loginId into Session (Session["loginId"])*/
                if (HttpContext.Current.Session["loginId"] == null)
                {
                    RouteValueDictionary redirectTargetDictionary = new RouteValueDictionary();

/*Here specify the action name which will be get executed when session get expire*/
                    redirectTargetDictionary.Add("action", "Index");

/*Here specify the controller name which will be get executed when session get expire*/
                    redirectTargetDictionary.Add("controller", "Home");

                    filterContext.Result = new RedirectToRouteResult(redirectTargetDictionary);
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
    }
}

Above class creates the custom attribute which will be used to maintain the session into MVC4 application.

Now you can use created Custom Attribute for session management. Here you have to put the custom attribute before the controller.

Following Code shows how to use Custom Attribute:

namespace ABC.Web.Controllers
{
/*Here I put the custom attribute which was applied at controller level means it is applicable to all actions that comes under the same controller */

    [CustomAuthorizeAttribute]

    public class XYZController : Controller
    {
      

No comments:

Post a Comment