Search code examples
asp.net-mvchttpcontextviewdatacontrollercontext

Can I access the ViewData from the HttpContext?


Im working with a project that sets variables such as the current user profile object in its authorize action filter, storing them in the ViewData for access by the following action method.

The action method then calls functionality from the repository. I'm trying to find a way to access the ViewData from the repository WITHOUT modifying the repository's method signature, and am hoping there is a way I can track back to it via the HttpContext.Current functionality which I can call from the repository.

Can anyone help with this? Just to be clear, the only code that I can modify is within the repository method :(

public class MyController : Controller {
    [MyAuthorize]                   // ViewData items are set here
    public void MyAction(int id)
    {
        new MyRepository().DoSomething(id); // Need to access ViewData items within this repository method and am unable to alter the method signature :(
    }
}

Solution

  • I'm pretty sure the answer is "no".

    When you review the ASP.NET MVC source code, ControllerBase instantiates a ViewData dictionary on first use. Then when you call View(), a new ViewResult is instantiated with the ControllerBase.ViewData dictionary as a parameter. It does not look like it gets applied to a public static property or class like HttpContext which you could access from inside your repository.

    I think your best bet would be to use HttpContext.Items which is built for this type of communication. Though probably not as ideal as just modifying the repository to accept the extra data.