ASP.NET MVC - Current Action from controller code?

只谈情不闲聊 提交于 2019-12-03 05:44:25

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.

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

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);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!