如何添加用户ID在mvc4中验证cookie

本文关键字:mvc4 验证 cookie ID 用户 何添加 添加 | 更新日期: 2023-09-27 18:09:50

如何添加用户ID TI AUTHENTICATED A cookie

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using System.Security.Cryptography;
using System.Text;
namespace project.Controllers
{
    public class LoginController : Controller
    {
        // GET: /Login/
        private DataContext db = new DataContext();
        public ActionResult Index()
        {
            return View();
        }
        [HttpPost]
        public ActionResult index(Loginmodel model)
        {
            if (ModelState.IsValid)
            {
                String username = model.Username;
                User Login = db.Users.Where(m => m.Name == username).First();
                String pass = Convert.ToBase64String(new MD5CryptoServiceProvider().ComputeHash(new UTF8Encoding().GetBytes(model.Password)));
                if (Login != null && pass == Login.Password)
                {
                    FormsAuthentication.SetAuthCookie(model.Username, false);
                    return RedirectToAction("index", "Project");
                }
                ModelState.AddModelError("", "Invalid username or password");
            }
           return View();
        }            
    }
}

如何添加用户ID在mvc4中验证cookie

这是一篇非常好的代码项目文章,它非常详细地解释了完成您正在尝试做的事情的不同方法。http://www.codeproject.com/Articles/36836/Forms-Authentication-and-Role-based-Authorization

if (!FormsAuthentication.CookiesSupported)
{
    //If the authentication ticket is specified not to use cookie, set it in the Uri
    FormsAuthentication.SetAuthCookie(encrypetedTicket, createPersistentCookie);
}
else
{
    //If the authentication ticket is specified to use a cookie, wrap it within a cookie.
    //The default cookie name is .ASPXAUTH if not specified 
    //in the <forms> element in web.config
    HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encrypetedTicket);
    //Set the cookie's expiration time to the tickets expiration time
    if(ticket.IsPersistent)
        authCookie.Expires =ticket.Expiration ;
    ////Set the cookie in the Response
    HttpContext.Current.Response.Cookies.Add(authCookie);
}