ASP.NET MVC - Current Action from controller code?

后端 未结 3 1318
感动是毒
感动是毒 2021-02-07 20:13

This is very similar to another recent question:

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

However, I want to get the name of the current actio

3条回答
  •  北荒
    北荒 (楼主)
    2021-02-07 20:49

    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 + "
    "); foreach (var param in method.GetParameters()) { b.AppendLine(param.Name + "
    "); } b.AppendLine("
    "); } return b.ToString() ; } }

提交回复
热议问题