2013-04-18 6 views
2

Как добавить пользовательский идентификатор TI ЗАВЕРЕНЫ печеньеКак добавить идентификатор пользователя Для аутентификации печенье в mvc4

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

Это очень хороший код проекта статьи, что объясняет довольно хорошей детализацией по-разному чтобы выполнить то, что вы пытаетесь сделать. 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); 
} 
+0

Вставить это в контроллер входа? мой код не распознал билет шифрования. –

+0

Извините, я не детализировал его. Билет поступает из FormsAuthenticationTicket formsTicket = new FormsAuthenticationTicket (...). Когда вы спросите билет обратно, билеты будут отправлены. Это будет то, что вы указали при его создании. Зашифрованный фрагмент может быть выполнен с использованием: string encrypetedTicket = FormsAuthentication.Encrypt (ticket); –

Смежные вопросы