开发者

Accessing current IPrinciple in a Master View in Asp.Net MVC

开发者 https://www.devze.com 2022-12-31 18:36 出处:网络
I currently have a abstract controller class that I all my controllers inherit from. I want to be able to use the current user (IPrinciple) object in my master page.

I currently have a abstract controller class that I all my controllers inherit from. I want to be able to use the current user (IPrinciple) object in my master page. I read that I could use the contructor of my abstract base controller class, that is I could do something like

public BaseController()
    {
        ViewData["UserName"] = this.User.Identity.Name;
    }

I could then access ViewData["UserName"] etc from my master page. My problem is that this.User开发者_开发百科 is null at this point. Does anybody know of a different approach?

Thanks in advance.


You could write an ActionFilter and in the OnActionExecuted event put the user inside ViewData:

public class UserActionFilterAttribute : ActionFilterAttribute
{
    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        base.OnActionExecuted(filterContext);
        filterContext.Controller.ViewData["UserName"] = filterContext.HttpContext.User.Identity.Name;
    }
}

And then decorate your base controller with this attribute:

[UserActionFilter]
public abstract class BaseController: Controller
{ }
0

精彩评论

暂无评论...
验证码 换一张
取 消