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

时间:2013-04-18 01:39:27

标签: c# asp.net-mvc asp.net-mvc-4

如何添加用户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();
        }            
    }
}

1 个答案:

答案 0 :(得分:1)

这是一篇非常好的代码项目文章,它非常详细地解释了完成您要完成的工作的不同方法。 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);
}
相关问题