Question

I'd like to hear your opinions and maybe better suggestions for the following scenario:

I have define a custom ActionFilter that does some job and comes out with some value. I would like to use that value in controller actions and in models.

Now, I could use TempData to pass this value from the ActionFilter to any controller action method, then distribute this value over to all models that get passed to returned views.

I'm sure it will work but this TempData will be there in session where and when nobody actually needs it anymore. The value is supposed to be used exclusively in the code during the time of a single request after which it effectively invalidates.

I have come up with two options:

  1. In ActionFilter, I set this value in TempData in OnActioExecuting() and I remove it in OnActionExecuted(). Do I understand it correctly that by the time OnActionExecuted is called, the controller action has finished, the response has already been generated and this TempData content hasn't made its way to the session YET?

  2. In any of my custom static classes (logic) I just define a public property for this value and I use it whenever needed. Will this static field not be lost between OnActionExecuting() and actually executing the controller method? Are there any other issues with possible loosing this value during the request processing on the server?

Are there any other/better options I havem't considered yet?

Was it helpful?

Solution

I have found that using ActionParameters makes your code very easily testable. You can do it like so:

// inside your actionfilter
public override void OnActionExecuting(ActionExecutinContext context)
{
    var someData = // ... load some data

    context.ActionParameters["someData"] = someData;
}


// and then in your action method
[ProvideSomeData]
public ViewResult Index(SomeData someData)
{
    // someData will be populated in here
}

OTHER TIPS

re: #2

Just wanted to point out that the problem with a static field is that multiple requests will all be using the same static field. If you have two requests executing concurrently there is a always a chance that request B will overwrite request A's value and you'll be using the wrong value when the action for request A executes.

I'd avoid using static members to hold request specific information.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top