在Identity中,您不需要擁有用戶對象進行身份驗證。您可以即時創建一些聲明並使用它們進行身份驗證。考慮一個簡單的例子:
[HttpPost]
public ActionResult AnonymousLogin()
{
var ident = new ClaimsIdentity(
new[]
{
// adding following 2 claim just for supporting default antiforgery provider
new Claim(ClaimTypes.NameIdentifier, "AnonymousUserID"),
new Claim("http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider", "ASP.NET Identity", "http://www.w3.org/2001/XMLSchema#string"),
new Claim(ClaimTypes.Name, "AnonymousUserID"),
},
DefaultAuthenticationTypes.ApplicationCookie);
HttpContext.GetOwinContext().Authentication.SignIn(
new AuthenticationProperties { IsPersistent = false }, ident);
return RedirectToAction("MyAction"); // auth succeed
}
現在你已經驗證的匿名用戶就像一個真正的用戶:
[Authorize]
public ActionResult MyAction()
{
// all authorized users could use this method don't matter how have been authenticated
// you have access current user principal
var username=HttpContext.User.Identity.Name;
}
真棒,我需要知道到底是什麼。我無法擺脫會話中的用戶對象,因爲我正在使用此網站的網站上工作,但我將我的方法分層以將此對象與Identity分開。非常感謝,這的確有幫助。 –