gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 13:43:38 25 4
gpt4 key购买 nike

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

最佳答案

这是一篇非常好的代码项目文章,非常详细地解释了完成您尝试做的事情的不同方法。 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);
}

关于c# - 如何添加用户 ID 以在 mvc4 中验证 cookie,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16073119/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com