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

孤者浪人 提交于 2020-01-13 16:24:06

问题


How to get Action and Controller names in ASP.Net MVC Core RC1 Application in Startup.cs?

I want to create a middleware and log the information (I want to Log detailed response to my Database, so I need Action and Controller info.) after following code in configure method of startup.cs -

 app.UseMvc(routes =>
{
     routes.MapRoute(
            name: "default",
            template: "{controller=User}/{action=Index}/{id?}");
 });

//Want to get Action and controller names here..

回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/36726180/how-to-get-action-and-controller-name-in-asp-net-core-mvc-app

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