![](/img/trans.png)
[英]Built-in helper to parse User.Identity.Name into Domain\Username
[英]Override User.Identity.Name in built-in MVC 4 authentication
我很難弄清楚這一點,真的需要這個工作。 我必須使用內置身份驗證覆蓋MVC 4中User.Identity.Name
的值。
這是我的Login()
控制器:
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Login(LoginModel model, string returnUrl)
{
//OLD CODES:
//if (ModelState.IsValid && WebSecurity.Login(model.UserName, model.Password, persistCookie: model.RememberMe))
//{
// return RedirectToLocal(returnUrl);
//}
// check if correct credentials
if (ModelState.IsValid && IsValidUser(model.UserName, model.Password))
return RedirectToAction("Index", "Home");
ModelState.AddModelError("", "The user name or password provided is incorrect.");
return View(model);
}
請注意,我將WebSecurity.Login(model.UserName, model.Password)
修改為WebSecurity.Login(model.UserName, model.Password)
IsValidUser(model.UserName,model.Password)
以檢查用戶帳戶,並且工作正常。
如果登錄成功,我想要覆蓋User.Identity.Name
的值。
這是我的IsValidUser(model.UserName,model.Password)
方法:
public bool IsValid(string _username, string _pwd)
{
_username = _username.Trim();
OleDbConnection conn = new OleDbConnection();
string strCon = string.Format(GlobalDBStrings.CONNSTRING, _username, _pwd);
conn.ConnectionString = strCon;
bool isConnected = false;
try
{
conn.Open();
if (conn.State.ToString() == "Open")
{
// I WANT TO MODIFY THE VALUE OF User.Identity.Name here
// User.Identity.Name = ?
isConnected = true;
}
}//try
catch (Exception ex)
{
}//catch
finally
{
conn.Close();
conn.Dispose();
}//finally
return isConnected;
}
到目前為止,我已經嘗試過User.Identity.Name = _username;
但根本沒用。
如果您使用的是FormsAuthentication,則需要在使用SetAuthCookie
方法重定向之前使用當前已驗證用戶的名稱設置cookie:
if (ModelState.IsValid && IsValidUser(model.UserName, model.Password))
{
FormsAuthentication.SetAuthCookie("FooBar", false);
return RedirectToAction("Index", "Home");
}
現在在目標控制器動作( /Home/Index
)上, User.Identity.Name
將是FooBar
。
通常這發生在您評論的方法中,如果您不發出表單身份驗證cookie,則您的用戶甚至不會通過身份驗證。
就你的IsValid
方法中的代碼而言,我只能說,IDisposable資源應該包含在using
語句中以確保正確釋放資源。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.