在MVC 6 Controller中创建会话(使用视图,使用实体框架)

时间:2016-03-01 23:11:18

标签: asp.net-mvc entity-framework linq

我正在尝试在UserAccountsController中创建一个会话

using System.Linq;
using Microsoft.AspNet.Mvc;
using Microsoft.AspNet.Mvc.Rendering;
using Microsoft.Data.Entity;
using POPPELWebsite.Models;

namespace POPPELWebsite.Controllers
{
    public class UserAccountController : Controller
    {

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

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

        [HttpPost]
        public ActionResult Register(UserAccount account)
        {
            if (ModelState.IsValid)
            {
                using (OurDbContext db = new OurDbContext())
                {
                    db.userAccount.Add(account);
                    db.SaveChanges();
                }

                ModelState.Clear();
                ViewBag.Message = account.FirstName + " " + account.LastName + " successfully registered.";
            }

            return View();
        }

        //Login
        public ActionResult Login()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Login(UserAccount user)
        {
            using (OurDbContext db = new OurDbContext())
            {
                var usr = db.userAccount.Single(u => u.Email == user.Email && u.Password == user.Password);
                if (usr != null)
                {
                    Session["UserID"] = usr.UserID.ToString;
                }
            }
        }

    }
}

我收到错误说

  

当前上下文中不存在名称Session。

我需要做这个部分来完成mvc的注册和登录教程

2 个答案:

答案 0 :(得分:0)

MVC 6中的Session类中不存在Controller属性,而是使用HttpContext.Session来访问会话属性。

例如:

// get values
string strValue = HttpContext.Session.GetString("StringKey");
int intValue = HttpContext.Session.GetInt32("IntKey");
byte[] byteArrayValue = HttpContext.Session.Get("ByteArrayKey");

// set values
HttpContext.Session.Set("ByteArrayKey", byteArrayValue);
HttpContext.Session.SetInt32("IntKey", intValue);
HttpContext.Session.SetString("StringKey", strValue);

答案 1 :(得分:0)

尝试一下。

public ActionResult Login(User users)
        {

            if (ModelState.IsValid)
            {
                using (DataContext db = new DataContext())
                {
                    var obj = db.Users.Where(u => u.Username.Equals(users.Username) && u.Password.Equals(users.Password)).FirstOrDefault();
                    if(obj !=null)
                    {
                        System.Web.HttpContext context = System.Web.HttpContext.Current;
                        context.Session["UserId"] = obj.UserId.ToString();
                        context.Session["Username"] = obj.Username.ToString();

                       return RedirectToAction("Dashboard");
                    }
                }
            }
            return View(users);

        }