发送授权用户的名字到_Layout.cshtm从基本控制器在c#
本文关键字:cshtm 控制器 Layout 用户 授权 | 更新日期: 2023-09-27 18:14:07
我有一个基本控制器在MVC 5,我想通过我的自定义字段,我添加到用户的身份到_Layout。但是我做不到我可以从另一个模型发送另一个数据视图,但我不能发送我的授权用户的名字到_Layout.cshtml这是我的Base Controller
public class BaseController : Controller
{
DataBaseContext db = new DataBaseContext();
public BaseController()
{
}
}
您可以使用ViewBag
:
public class BaseController : Controller
{
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
ViewBag.Name = User.Identity.Name ?? "Anonymouse user";
base.OnActionExecuting(filterContext);
}
}
在_Layout.cshtml
中你可以很容易地这样访问Name
<span>@ViewBag.Name</span>
更新:如果你想检索自定义用户的数据,试试这个:
public class BaseController : Controller
{
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
var store = new UserStore<ApplicationUser>(new ApplicationDbContext());
var userManager = new UserManager<ApplicationUser>(store);
ApplicationUser user = userManager.FindByNameAsync(User.Identity.Name).Result;
ViewBag.Name = user != null ? user.FullName : "Aanonymouse";
base.OnActionExecuting(filterContext);
}
}
@{
System.Security.Principal.IIdentity me = HttpContext.Current.User.Identity;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>@ViewBag.Title - My ASP.NET Application</title>
</head>
<body>
<p>Hello @me.Name</p>
</body>
</html>