Get Controller and Action Name from Within Controller

Get controller and action name from within controller?

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

How to get main controller and action name in .net

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

Get Parameters along with controller and action name from endpoint

// GET: api/PatientSearch/5
[HttpGet("{id}", Name = "Get")]
public string Get(int id)
{
var parameters = MethodBase.GetCurrentMethod().GetParameters();
var paramNames = String.Join(", ", parameters.Select(p => p.Name)); // myString, myInt

return this.ControllerContext.RouteData.Values["action"] + "{"+ paramNames + "}";
}

Screenshots of test result:


public string Get(int id)

Sample Image

public string Get(int id, string str)

Sample Image

Get MVC controller name from controller's class

DefaultHttpControllerSelector has a protected method to get the controller's name base on the default <controller name>Controllerclass naming convention.

Going as far as inheriting DefaultHttpControllerSelector in a utility class could do the trick. I don't need this anymore so I'm leaving the implementation to your imagination.

Get controller and action name from AuthorizationHandlerContext object

var mvcContext = context.Resource as AuthorizationFilterContext;
var descriptor = mvcContext?.ActionDescriptor as ControllerActionDescriptor;
if (descriptor != null)
{
var actionName = descriptor.ActionName;
var ctrlName = descriptor.ControllerName;
}

Get executing controller and action name in web API

Just use action and controller contexts

var actionName = this.ActionContext.ActionDescriptor.ActionName;
var controllerName= this.ControllerContext.ControllerDescriptor.ControllerName;


Related Topics



Leave a reply



Submit