ram*_*ilu 3 c# asp.net-core-mvc asp.net-core asp.net-core-1.0
如何在Application中获取Action和Controller命名?ASP.Net MVC Core RC1Startup.cs
我想创建一个中间件和登录下面的代码后的信息(我想记录详细的回应我的数据库,所以我需要行动和控制器的信息。)configure的方法startup.cs-
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=User}/{action=Index}/{id?}");
});
//Want to get Action and controller names here..
Run Code Online (Sandbox Code Playgroud)
您将需要将IActionDescriptorCollectionProvider服务注入到中间件中。由此,您可以使用属性ActionDescriptors.Items获取的列表ActionDescriptor,其中包含该操作的所有路线值。如果将其投射到ControllerActionDescriptor,则可以访问ControllerName和ActionName。
这就是我在自定义异常处理程序中间件中执行此操作的方法。
using System.Diagnostics;
frame = new StackTrace(e, true).GetFrame(0);
controller = frame.GetMethod().DeclaringType.FullName;
action = frame.GetMethod().ToString();
Run Code Online (Sandbox Code Playgroud)
如果您想查看中间件项目,请点击此处的链接 CustomExceptionHandler
编辑:
您还可以在操作过滤器中进行日志记录。动作过滤器的 OnActionExecuting() 方法有一个 ActionExecutingContext 参数。通过该参数,您可以获得有关请求的各种信息。以下是获取控制器和操作名称的方法。我建议在单独的线程中执行此操作以帮助提高响应能力。
public override void OnActionExecuting(ActionExecutingContext context)
{
var t = Task.Run(() => {
controller = context.Controller.ToString();
action = context.ActionDescriptor.Name;
//Log to DB
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7478 次 |
| 最近记录: |