【发布时间】:2011-01-06 10:37:00
【问题描述】:
在 MVC2 中,我使用 Page.User.Identity.Name 使用 <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>
如何在 MVC3 中使用它?
【问题讨论】:
标签: asp.net-mvc-3
在 MVC2 中,我使用 Page.User.Identity.Name 使用 <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>
如何在 MVC3 中使用它?
【问题讨论】:
标签: asp.net-mvc-3
你总是可以这样做:
@Html.ViewContext.HttpContext.User.Identity.Name
但不要。
通常视图不应尝试获取此类信息。它在那里显示控制器传递的任何信息。它应该是由控制器操作传递的模型类的强类型。
所以在渲染这个视图的控制器动作中:
[Authorize]
public ActionResult Index()
{
var model = new MyViewModel
{
Username = User.Identity.Name
}
return View(model);
}
现在可以在视图内部随意使用这些信息:
@Model.Username
【讨论】:
m using FormsAuthentication.RedirectFromLoginPage(user.Name, model.RememberMe); and in another view im 试图在 _LogOnPartial.cshtml 中使用 @if(Request.IsAuthenticated) { s the use of _LogOnPartial.cshtml in that case? and I just cant 对所有视图都这样做?
FormsAuthentication.RedirectFromLoginPage。执行重定向的正确方法是在将身份验证 cookie 设置为响应后(使用 FormsAuthentication.SetAuthCookie)到 return RedirectToAction("LoggedIn", "SomeController")。然后在 LoggedIn 操作中简单地获取用户名并将其传递给视图模型。所以使用@Model.Username 而不是@Page.User.Identity.Name。
@Html.ViewContext.HttpContext.User.Identity.Name。
SetAuthCookie 与RedirectFromLoginPage 完全相同,只是它不执行重定向,因为正如我所解释的,ASP.NET MVC 中的重定向应该由返回 RedirectToAction 结果的控制器操作执行。
MVC 2
<%: this.Page.User.Identity.Name %>
MVC 3
@this.User.Identity.Name
【讨论】:
我遇到了同样的问题。我使用this tutorial 解决了这个问题。
简而言之,在你看来,把这段代码:
@Context.User.Identity.Name
只需确保项目设置为使用 windows 进行身份验证即可。
【讨论】: