How to use MVC 4 session with C#?

Asked

Viewed 5,794 times

6

My scenario is as follows. I have an MVC 4 application. In my controller I check the logged in user and password. (I think) I put the user data in a session after the data is checked and correct.

My pages are cshtml (Razor). And I have a master page that will use the data from Session to show the logged in user for example.

If the login data is not correct the session will be empty and I will redirect to the login page.

Doubts:

  • How to open and close the session?
  • How to set downtime to close it?
  • What it takes for the system to only allow direct access through Urls after login and Session active.

My Login Screen Action after sending the data:

    [HttpPost]
    public ActionResult Index(UsuarioDTO dto)
    {
        UsuarioDTO ValidarLogin = null;

        UsuarioDTO usuario = new UsuarioDTO();
        usuario.Login = dto.Login;
        usuario.Senha = dto.Senha;

        negocio = new AeroJetNEGOCIO();

        try
        {
            ValidarLogin = negocio.Login.LogarUsuario(usuario);

            usuario = ValidarLogin;

            Session["usuarioLogado"] = usuario;                   

            return RedirectToAction("Index", "CadastroCliente");
        }
        catch (Exception e)
        {
            ViewBag.classe = "alert";
            ViewBag.msg = e.Message;
            return View();
        }
    }

NOTE: This part I include I don’t even know how it behaves. It was just an attempt.

This screen redirects to another Action from another Controller that is a screen for an already logged in user.

    public ActionResult Index()
    {
         return View();
    }

NOTE: I don’t know if I should put some code to validate Session ai. I need help on this part.

If you need the cshtml of the master page or the page that enters after login I post.

1 answer

4

Create a Sessionmanager

public static class SessionManager
{
    public static void RegisterSession(string key, object obj)
    {
        System.Web.HttpContext.Current.Session[key] = obj;
    }

    public static void FreeSession(string key)
    {
        System.Web.HttpContext.Current.Session[key] = null;
    }


    public static bool CheckSession(string key)
    {
        if (System.Web.HttpContext.Current.Session[key] != null)
            return true;
        else
            return false;
    }

    public static bool CheckSession(string key, System.Web.HttpContextBase contexto)
    {
        if (contexto.Session[key] != null)
            return true;
        else
            return false;
    }

    public static object ReturnSessionObject(string key)
    {
        if (CheckSession(key))
            return System.Web.HttpContext.Current.Session[key];
        else
            return null;
    }

    public static object ReturnSessionObject(string key, System.Web.HttpContextBase contexto)
    {
        if (CheckSession(key, contexto))
            return contexto.Session[key];
        else
            return null;
    }
}

Create a Customauthorizeattribute

public struct SessionKeys
{
    public const string Usuario = "Usuario";
}

public class ResearchAuthorizeAttribute : AuthorizeAttribute
{
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        if (SessionManager.CheckSession(SessionKeys.Usuario) == true)
            return true;
        else
            return false;
    }

    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {
        if (SessionManager.CheckSession(SessionKeys.Usuario) == false)
        {
            filterContext.Result = new RedirectToRouteResult(
                            new RouteValueDictionary 
                    {
                        { "action", "Login" },
                        { "controller", "Research" }
                    });
        }
        else
            base.HandleUnauthorizedRequest(filterContext);
    }
}

Create a Customautenticadomodelbinder

class ResearchAutenticadoModelBinder : IModelBinder
{
    public object GetValue(ControllerContext controllerContext)//, string modelName, Type modelType, ModelStateDictionary modelState)
    {
        var modelo = new ResearchAutenticadoBindModel();
        modelo.Usuario = SessionManager.ReturnSessionObject(SessionKeys.Usuario, controllerContext.HttpContext).ToString();
        return modelo;
    }

    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        if (controllerContext == null)
            throw new ArgumentNullException("controllerContext", "controllerContext is null.");
        if (bindingContext == null)
            throw new ArgumentNullException("bindingContext", "bindingContext is null.");

        return GetValue(controllerContext);
    }
}

Add your Custommodelbinder to Application_start

ModelBinders.Binders.Add(typeof(ResearchAutenticadoBindModel), new ResearchAutenticadoModelBinder());

Now you can register the login Controllers:

SessionManager.RegisterSession(SessionKeys.Usuario, "Usuario XYZ");

And you can use your Authorize Actions restricted:

    [ResearchAuthorize]
    public ActionResult New(ResearchAutenticadoBindModel login)
    {
        return Edit(login, 0);
    }
  • Thank you very much tomorrow I’ll be your solution.

  • Sessionmanager, Customauthorizeattribute and Customauthenticatdomodelbinder are separate class files? What name should I put on them?

  • @Joaopaulo, that’s right, Voce can give the name you want to these classes. I basically used these three followed by a self-explanatory suffix.

Browser other questions tagged

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