views:

645

answers:

3

This is very similar to another recent question:

http://stackoverflow.com/questions/362514/asp-net-mvc-current-action

However, I want to get the name of the current action from within controller code.

So within the code of a function that's being called by an Action, I want to get a string of the name of the current Action.

Is this possible?

A: 

The only way I can think of, is to use the StackFrame class. I wouldn't recommend it if you're dealing with performance critical code, but you could use it. The only problem is, the StackFrame gives you all the methods that have been called up to this point, but there's no easy way to identify which of these is the Action method, but maybe in your situation you know how many layers up the Action will be. Here's some sample code:

[HandleError]
public class HomeController : Controller
{
    public void Index()
    {
        var x = ShowStackFrame();
        Response.Write(x);
    }

    private string ShowStackFrame()
    {
        StringBuilder b = new StringBuilder();
        StackTrace trace = new StackTrace(0);

        foreach (var frame in trace.GetFrames())
        {
            var method = frame.GetMethod();
            b.AppendLine(method.Name + "<br>");

            foreach (var param in method.GetParameters())
            {
                b.AppendLine(param.Name + "<br>");
            }
            b.AppendLine("<hr>");
        }

        return b.ToString() ;
    }
}
BFree
+5  A: 

You can access the route data from within your controller class like this:

var actionName = ControllerContext.RouteData.GetRequiredString("action");

Or, if "action" isn't a required part of your route, you can just index into the route data as per usual.

Ty
A: 

Well if you are in the controller you know what action is being called. I am guessing that you have a class that is being used in the controller that needs to behave differently based on the action that is being called. If that is the case then I would pass a string representation of the action into the object that needs this information from within the action method. Some sample code from you would really clarify what you are needing to do. Here is some sample code that I am thinking:

public ActionResult TestControllerAction()
{
     var action = new TestControllerAction();
     var objectWithBehaviorBasedOnAction = new MyObjectWithBehaviorBasedOnAction();
     objectWithBehaviorBasedOnAction.DoSomething(action);    
}

public class MyObjectWithBehaviorBasedOnAction: IMyBehaviorBasedOnAction
{
    public void DoSomething(IControllerAction action)
    {
      // generic stuff
    }
    public void DoSomething(TestControllerAction action)
    {
       // do behavior A
    }
    public void DoSomething(OtherControllerAction action)
    {
        // do behavior b
    }
}

public interface IMyBehaviorBasedOnAction
{
   void DoSomething(IControllerAction action);
}
Michael Mann