3

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 :(
    }
}
Jimbo
  • 22,379
  • 42
  • 117
  • 159
  • So this is in a filter before it gets to the repo? –  Jun 12 '14 at 12:44
  • Correct, I will post a code example. Thanks – Jimbo Jun 12 '14 at 12:47
  • The only way you could do this is by registering the ViewData into an IoC or something and resolve it from inside the repo... That doesn't sound v clean though IIH –  Jun 12 '14 at 14:25

1 Answers1

1

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.

Steven V
  • 16,357
  • 3
  • 63
  • 76
  • If you get the viewdata inside a filter and put it somewhere static you acn grab it later but yeah - messy –  Jun 12 '14 at 15:30