我的用户已通过身份验证,但具有存储在FormsAuthenticationTicket中,然后是cookie中的额外信息。在布局页面上查看自定义用户数据的模型
// Custom UserData will contain the following | seperated values:
// [ FullName | ContactNumber1 | ContactNumber2 ]
string userData = fullName + "|" + contactNumber1 + "|" + contactNumber2
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
1,
userName,
DateTime.Now,
DateTime.Now.AddMinutes(20),
false,
userData,
FormsAuthentication.FormsCookiePath);
创建的Cookie等等等等
所有这一切工作正常。
im使用MVC 3和剃刀
我有一个显示的全名/ ContactNumber等等等等在页面的顶部的foo.Layout.cshtml。
我可能包括在foo.Layout.cshtml顶部代码提取显示这些值:
@{
FormsAuthenticationTicket ticket = ((FormsIdentity)User.Identity).Ticket;
// Custom UserData will contain the following | seperated values:
// [ FullName | ContactNumber1 | ContactNumber2 ]
string[] userData = ticket.UserData.Split(new char[] { '|' });
string fullName = userData[0];
string contactNumber1 = userData[1];
string contactNumber2 = userData[2];
}
<div>@fullName</div>
<div>@contactNumber1</div>
<div>@contactNumber2</div>
这意味着我不必包括我控制器这段代码,但说实话,我不喜欢它和我的实际应用程序(不同的值)我需要在我的大部分视图中的值包括布局。
所以我一直在争论,包括我的控制器中的代码:
创建一个视图模型:
public class UserViewModel {
public string FullName { get; set; }
public string ContactNumber1 { get; set; }
public string ContactNumber2 { get; set; }
}
创建控制器
public class FooController : Controller {
private readonly _userViewModel = null;
public FooController() {
// NOTE this would actually be behind an interface in some type of
// repository/service pattern and injected but for the sake
// of easy conversation ive put it here.
FormsAuthenticationTicket ticket = ((FormsIdentity)User.Identity).Ticket;
// Custom UserData will contain the following | seperated values:
// [ FullName | ContactNumber1 | ContactNumber2 ]
string[] userData = ticket.UserData.Split(new char[] { '|' });
_userViewModel = new UserViewModel();
userViewModel.FullName = userData[0];
userViewModel.ContactNumber1 = userData[1];
userViewModel.ContactNumber2 = userData[2];
}
public ActionResult Index() {
(HOWEVER_SET_ON_LAYOUT_PAGE) = userViewModel.FullName;
// If not posting ViewModel
(HOWEVER_SET_ON_THIS_PAGE) = userViewModel.FullName;
// If posting ViewModel
return View(_userViewModel);
}
也许一些本可以在控制器工厂里面放。
我只是在寻找讨论或其他人如何接近这个相当常见的设置的想法。
我的实际任务是通过布局在每个页面的顶部显示用户全名,并在填写和提交的各种表单的底部显示全名(和其他数据)。回传后,全名将被重新读取,并发送到与其他表单域一起存储。这是有道理的,是否真的是那个时候: -/
你能提供一个实际的例子吗? – 2012-06-27 20:52:12