wtuqi
2/23/2020 - 4:45 AM

ASP.NET的Cookie与SESSION

 环境[MVC4]
  <HttpPost()> _
    <AllowAnonymous()> _
    <ValidateAntiForgeryToken()> _
    Public Function Login(ByVal model As UserProfile, ByVal returnUrl As String) As ActionResult
        Dim q = (From m In db.UserProfiles
                    Where m.UserName = model.UserName And m.Password = model.Password
                    Select New With {.a = m.UserName, .b = m.Password}).ToList()
        If ModelState.IsValid And q.Count > 0 Then
            '加密当前用户名并装截至cookie
            Dim ticket As FormsAuthenticationTicket = New FormsAuthenticationTicket(model.UserName, False, 120)
            Dim encryptedTicket As String = FormsAuthentication.Encrypt(ticket) '加密
            Dim authCookie As HttpCookie = New HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket)
            Response.Cookies.Add(authCookie)
            Return RedirectToLocal(returnUrl)
        End If

        ' If we got this far, something failed, redisplay form
        ModelState.AddModelError("", "错误的用户名或密码.")
        Return View(model)
    End Function


        '在GET中获取cookie用户资料解密
        <HttpGet()>
        Function Updata() As ActionResult '无<HttpPost()|HttpGet()则默认重用页面>
            Dim Uname As String = Nothing
            Dim authCookie As HttpCookie = Request.Cookies(FormsAuthentication.FormsCookieName)
            If authCookie IsNot Nothing Then
                Dim authTicket As FormsAuthenticationTicket = FormsAuthentication.Decrypt(authCookie.Value)
                Uname = authTicket.Name '获取cookie用户名
                '下面作处理用户名权限判断
                Dim q = (From m In db.UserProfiles
                Where m.Us = 1 And m.UserName = Uname
                Select New With {.a = m.Us}).ToList()
                If q.Count > 0 Then
                    Return View(db.Students.ToList())
                    '如果
                End If
            End If
            Return View("~/Views/Home/index.Vbhtml", db.Students.ToList())
        End Function
//实例应用 环境MVC4
string uname = Request.Params["uname"].ToString(); //接受页面
string pwd=Request.Form["pword"].ToString();
var query = (from t in db.sys_user where t.user_name == uname & t.user_pass==pwd select t);
if (query.Count() > 0)
{
    //添加用户数据
    FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(uname, false, 120);
    string encryptedTicket = FormsAuthentication.Encrypt(ticket);
    //加密
    HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
    Response.Cookies.Add(authCookie);
    //验证成功跳转
    return RedirectToAction("Index", "task", new { id =2});
}
Response.ClearContent();
Response.Write("<script language=javascript>alert('您没有权限访问,请与网络管理员联系!');</script>");
Session是在服务端保存的一个数据结构,用来跟踪用户的状态,这个数据可以保存在集群、数据库、
文件中;
Cookie是客户端保存用户信息的一种机制,用来记录用户的一些信息,也是实现Session的一种方式;
string oldcode = Session["SecurityCode"] as string;
string code = CreateRandomCode(5);
Session["SecurityCode"] = code;