views:

197

answers:

3

Hi,

I've just started a new project in ASP.net 4.0 with MVC 2.

What I need to be able to do is have a custom hook at the start and end of each action of the controller.

e.g.

public void Index() {  
    *** call to the start custom hook to externalfile.cs (is empty so does nothing)

    ViewData["welcomeMessage"] = "Hello World";

    *** call to the end custom hook to externalfile.cs (changes "Hello World!" to "Hi World")

    return View();
}

The View then see welcomeMessage as "Hi World" after being changed in the custom hook.

The custom hook would need to be in an external file and not change the "core" compiled code. This causes a problem as with my limited knowledge ASP.net MVC has to be compiled.

Does anyone have any advice on how this can be achieved?

Thanks

+1  A: 

An event based plugin system where you can dynamically call script code. So creating (for example) iron python scripts that get called when events are raised by the controller.

Doesn't have to be iron python, but that would make the most sense that I can see.

Simon
I've done similar to this, albeit not in MVC.Works well.
Russ C
A: 

How about override OnActionExecuting/OnActionExecuted and use MEF(Import,Export other assembly code)?

takepara
Why use MEF when this concept is already in the MVC framework as an ActionFilter?
Ryan
Because it thought dynamic injection code in the action filter is executed.
takepara
+2  A: 

You create your own class based on the ActionFilterAttribute. It has the following hooks.

  1. OnActionExecuted
  2. OnActionExecuting
  3. OnResultExecuted
  4. OnResultExecuting

For example,

public class MyFilterAttribute : ActionFilterAttribute
{
    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        var controller = filterContext.Controller;

        controller.ViewData["welcomeMessage"] = "Hi World!";
        controller.TempData["Access_My_TempData"] = "Some Value";

        base.OnActionExecuted(filterContext);
    }
}

You can also check what type of [Action] the Action method is performing.

if ((filterContext.Result is RedirectResult) || (filterContext.Result is RedirectToRouteResult))
{
    // do something only if we are redirecting to a different action
}
else if (filterContext.Result is ViewResult)
{
    // this is just a normal View action
}

Oh I forgot to show how to use the attribute.
You just decorate on top of your Action Method.

[MyFilterAttribute]
public ActionResult MyActionMethod()
{
    return View();
}
stun
If you don't want to manually put the attribute on every action, I believe you can create a common base controller type and put the attribute on the type itself.
Ryan
This looks like the sort of thing I'm hoping to do.Thanks
Adrian