Search code examples
asp.net.netasp.net-coremodel-view-controllerasp.net-core-mvc

How to get main controller and action name in .net


I have a .net core mvc web project and i'm trying to get action and controller name in the action. For example

 string actionName = ControllerContext.RouteData.Values["action"].ToString();
 string controllerName = ControllerContext.RouteData.Values["controller"].ToString();

those codes are giving me the value of controller and action but i wanna know which page did send that post.

For example: we have HomeController and RequestQuote action inside of that controller. If another page triggers that RequestQuote action from different controller and action, i wanna get that controller and actions name. I hope i can be clear what i'm trying to meant it.


Solution

  • Here is a working demo you could follow:

    LoginController

    public class LoginController : Controller
    {
        public IActionResult Index()
        {
            return RedirectToAction("RequestQuote", "Home");
        }
    }
    

    HomeController

    public class HomeController : Controller
    {
        public ActionResult RequestQuote()
        {
            string controllerName = HttpContext.Session.GetString("controller");
            string actionName = HttpContext.Session.GetString("action");
            return View();
        }
    }
    

    ActionFilter:

    public class CustomFilter : IActionFilter
    {
        public void OnActionExecuted(ActionExecutedContext context)
        {
            string actionName = context.HttpContext.Request.RouteValues["action"].ToString();
            string controllerName = context.HttpContext.Request.RouteValues["controller"].ToString();
            context.HttpContext.Session.SetString("controller", controllerName);
            context.HttpContext.Session.SetString("action", actionName);
        }
        public  void OnActionExecuting(ActionExecutingContext filterContext)
        {
            
        }      
    }
    

    Register the service in Startup.cs:

    services.AddControllersWithViews(opt => {
        opt.Filters.Add(new CustomFilter());
    });