【问题标题】:ASP.NET MVC - Current Action from controller code?ASP.NET MVC - 来自控制器代码的当前操作?
【发布时间】:2009-09-11 02:49:07
【问题描述】:

这与最近的另一个问题非常相似:

How can I return the current action in an ASP.NET MVC view?

但是,我想从 controller 代码中获取当前操作的名称。

因此,在被 Action 调用的函数代码中,我想获取当前 Action 名称的字符串。

这可能吗?

【问题讨论】:

    标签: c# asp.net-mvc-2 controller action


    【解决方案1】:

    您可以像这样从控制器类中访问路由数据:

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

    或者,如果“操作”不是您路线的必需部分,您可以照常索引路线数据。

    【讨论】:

      【解决方案2】:

      我能想到的唯一方法是使用StackFrame 类。如果您正在处理性能关键代码,我不会推荐它,但您可以使用它。唯一的问题是,StackFrame 为您提供了到目前为止已调用的所有方法,但是没有简单的方法来确定其中哪些是 Action 方法,但也许在您的情况下,您知道 Action 将向上多少层是。下面是一些示例代码:

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

      【讨论】:

        【解决方案3】:

        好吧,如果您在控制器中,您就会知道正在调用什么动作。我猜你有一个在控制器中使用的类,它需要根据被调用的操作来表现不同。如果是这种情况,那么我会将操作的字符串表示形式传递给需要从操作方法中获取此信息的对象。您提供的一些示例代码将真正阐明您需要做什么。这是我正在考虑的一些示例代码:

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2011-04-03
          • 2021-02-07
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多