开发者

How to add custom hooks to controllers in ASP.NET MVC2

开发者 https://www.devze.com 2023-01-01 03:47 出处:网络
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.

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开发者_Python百科 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


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();
}


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.


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

0

精彩评论

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