开发者

Share an object application-wide in ASP.NET MVC3

I have an ASP.NET MVC3 web application with C# and Razor.

Through a form in a View I get the Context.User.Identity.Name submitted to an action method in a Controller A.

I would like to have available this variable application-wide (between multiple controllers). Now I am just able to assign it to a global variable _UserName within the Controller A, but of course it is not available in Co开发者_如何学Gontroller B.

Is it possible to do that?

Thanks

Francesco


If you are accessing this in any controller, you should use HttpContext.User.Identity in your controller methods - it will be available there. No need to store in the session.


Create a parent controller from which all your controllers inherit from and set the variable there. You could do a number of things with it from there--wrap it in a view model, put some user details into the ViewBag, etc

public class UserController : Controller
{
    // create your own User class with as many properties as you need
    protected User user { get; set; }

    public UserController()
    {
        user = // get user from db, wherever
    }
}

Then, just inherit from UserController

public class ControllerA : UserController
{
    public ActionResult DoSomething()
    {
        user.Property = 123;
    }
}


You should look into caching and possibly using the users session store this information.

Check out this question.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜