Malek Ben el ouafi Malek Ben el ouafi - 3 months ago 19
C# Question

Session management in asp.net Code first

I use a custom authentication in my project, and I can't manage the session to get the user permission in route. This is my code :

Admin controller

// POST: administration
[HttpPost]
public ActionResult Login(Admin admin)
{
var user = AdminContext.admins.SingleOrDefault(u => u.Email == admin.Email && u.Pass == admin.Pass);

if (user != null)
{
Session["adminID"] = user.adminID;
Session["adminNom"] = user.Nom.ToString() + " " + user.Prenom.ToString();

if (System.IO.File.Exists(Server.MapPath("~" + user.Photo)))
{ Session["adminPhoto"] = "~" + user.Photo; }
else
{ Session["adminPhoto"] = "~/Content/TemplateAdmin/assets/images/no_img.png"; }

return RedirectToRoute("Dashboard");
}
else
{
ModelState.AddModelError("", "Email ou mot de passeest incorrect");
return View("~/Views/Administration/Login.cshtml");
}
}


Project route

public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

routes.MapRoute(
name: "LoginAdmin",
url: "administration",
defaults: new { controller = "Admin", action = "Login" }
);

routes.MapRoute(
name: "Dashboard",
url: "administration/dashboard",
defaults: new { controller = "Dashboard", action = "Index"}
);

routes.MapRoute(
name: "Profile",
url: "administration/profile",
defaults: new { controller = "Admin", action = "Profil" }
);

routes.MapRoute(
name: "Gestion_admins",
url: "administration/gestion_admins/{action}/{id}",
defaults: new { controller = "Admin", action = "Index", id = UrlParameter.Optional }
);
}


Should I check session for all ActionResult in my project ? Like this :

// POST: Profil
[HttpPost]
public ActionResult Profil(Admin model)
{
if (Session["adminID"] != null)
{
model.adminID = Convert.ToInt32(Session["adminID"]);
}
}

Answer

I solved the problem, i share it :

I create a new classe AdminAuthorize :

public class AdminAuthorize : AuthorizeAttribute
{

    baseContext AdminContext;

    public AdminAuthorize()
    {
        AdminContext = new baseContext();
    }

    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {

        //check cookie

        string email = string.Empty, password = string.Empty;
        Admin TempAdmin = null;

        if (httpContext.Response.Cookies["adminEmail"] != null)
            email = httpContext.Response.Cookies["adminEmail"].Value;

        if (httpContext.Response.Cookies["adminPass"] != null)
            password = httpContext.Response.Cookies["adminPass"].Value;

        if (!String.IsNullOrEmpty(email) && !String.IsNullOrEmpty(password))
            TempAdmin = AdminContext.admins.SingleOrDefault(u => u.Email == email && u.Pass == password);

            if (TempAdmin != null)
            {
                httpContext.Session["adminID"] = TempAdmin.adminID;
                httpContext.Session["adminNom"] = TempAdmin.Nom.ToString() + " " + TempAdmin.Prenom.ToString();

                if (System.IO.File.Exists(httpContext.Server.MapPath("~" + TempAdmin.Photo)))
                { httpContext.Session["adminPhoto"] = "~" + TempAdmin.Photo; }
                else
                { httpContext.Session["adminPhoto"] = "~/Content/TemplateAdmin/assets/images/no_img.png"; }

                return true;
            }


        // Now check the session:
        if (httpContext.Session["adminID"] != null)
        {
            return true;
        }

        return false;
    }
}

And i just use it in the Admincontroller

[AdminAuthorize]
        public ActionResult Profil()
        {
            int id = Convert.ToInt32(Session["adminID"]);

        }

It work !!

Comments