我是用 cookie 做的 :)...你可能会发现我的回答很有用:What OpenID solution is really used by Stack Overflow?
我还写了一篇关于它的简单博文:http://codesprout.blogspot.com/2011/03/using-dotnetopenauth-to-create-simple.html
public class User
{
[DisplayName("User ID")]
public int UserID{ get; set; }
[Required]
[DisplayName("Open ID")]
public string OpenID { get; set; }
[DisplayName("User Name")]
public string UserName{ get; set; }
}
在我的示例中,我使用 OpenID 登录并将其存储在 cookie 中,但您可以在 cookie 中存储其他信息,例如用户名:
public class FormsAuthenticationService : IFormsAuthenticationService
{
public void SignIn(string userName, bool createPersistentCookie)
{
if (String.IsNullOrEmpty(serName)) throw new ArgumentException("The user name cannot be null or empty.", "UserName");
FormsAuthentication.SetAuthCookie(userName, createPersistentCookie);
}
public void SignOut()
{
FormsAuthentication.SignOut();
}
}
更新 2.0:
像这样的东西怎么样(这是视图):
<%
if (Request.IsAuthenticated)
{
string name = Request.Cookies[Page.User.Identity.Name] == null ? string.Empty : Request.Cookies[Page.User.Identity.Name].Value;
if (string.IsNullOrEmpty(name))
{
name = Page.User.Identity.Name;
}
%>
[<%: Html.ActionLink(name, "Profile", "User")%> |
<%: Html.ActionLink("Log out", "LogOut", "User") %> |
<%
}
else
{
%>
[ <%: Html.ActionLink("Log in", "LogIn", "User") %> |
<%
}
%>
和控制器,大概你在登录后被带到一个Profile页面(或者你可以在LogIn方法中设置Response.Cookies)并且当你加载模型时你设置在 cookie 中显示名称:
[Authorize]
[HttpGet]
public ActionResult Profile(User model)
{
if (User.Identity.IsAuthenticated)
{
userRepository.Refresh();
model = userRepository.FetchByOpenID(User.Identity.Name);
// If the user wasn't located in the database
// then add the user to our database of users
if (model == null)
{
model = RegisterNewUser(User.Identity.Name);
}
Response.Cookies[model.OpenID].Value = model.DisplayName;
Response.Cookies[model.OpenID].Expires = DateTime.Now.AddDays(5);
return View(model);
}
else
{
return RedirectToAction("LogIn");
}
}
您可以在我的一个小项目中看到这一切:mydevarmy。我将很快发布用户个人资料,您将能够更改显示名称(现在是自动生成的)。