问题
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