How to get Action and Controller name in ASP.Net Core MVC app?

喜欢而已 提交于 2019-12-05 22:43:01

You'll want to inject the IActionDescriptorCollectionProvider service into your middleware. From that, you can use the property ActionDescriptors.Items to get a list of ActionDescriptor, which has all the route values for that action. If you cast that to ControllerActionDescriptor, you'll have access to ControllerName and ActionName.

This is how I do it in my custom exception handler middleware.

using System.Diagnostics;

frame = new StackTrace(e, true).GetFrame(0);
controller = frame.GetMethod().DeclaringType.FullName;
action = frame.GetMethod().ToString();

If you'd like to checkout the middleware project, here's the link CustomExceptionHandler

EDIT:
You could also do your logging in an action filter. The OnActionExecuting() method of an action filter has an ActionExecutingContext parameter. With that parameter you can get all kinds of info about the request. Below is how you would get the controller and action name. And I would suggest doing it in a separate thread to help with responsiveness.

public override void OnActionExecuting(ActionExecutingContext context)
{
    var t = Task.Run(() => {
        controller = context.Controller.ToString();
        action = context.ActionDescriptor.Name;

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