Question

I am building a BaseController where I want to have a function that goes out and checks if the user is authenticated and fill a variable with either the username or "Guest". I then need to access that variable from my layout view (to print things like "hello, USER"). I have successfully built the method but what I am unable to figure out is how to assign the result to a variable that the layout view (or any other view tied to a controller that inherits from the BaseController) can access.

Était-ce utile?

La solution

You can store it in the ViewBag in a base controller:

public class BaseController : Controller {
    protected override void OnActionExecuting(ActionExecutingContext filterContext) {
        ViewBag.UserName =
            filterContext.HttpContext.User.Identity.IsAuthenticated
                ? filterContext.HttpContext.User.Identity.Name
                : "GUEST";

        base.OnActionExecuting(filterContext);
    }
}

Have all of your controllers inherit from the base controller.. then your views can become:

<p>Hello @ViewBag.UserName</p>
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top