Ich richte eine benutzerdefinierte Middleware für meine .NET Core-Anwendung ein, um Ausnahmefehler zu protokollieren, und habe Folgendes in der Startup.cs, um meine Kontexte zu registrieren:
 
       services.AddHttpContextAccessor();
   services.AddSingleton<IActionContextAccessor, ActionContextAccessor>();
 
    Und in meiner Konfiguration habe ich Folgendes hinzugefügt, um eine benutzerdefinierte Middleware zu verwenden:
 
       app.UseMiddleware<CustomMiddleware>();
 
    Meine benutzerdefinierte Middleware-Klasse lautet wie folgt:
 
     public class CustomMiddleware
 {
    private readonly RequestDelegate next;
    public CustomMiddleware(RequestDelegate next)
    {
        this.next = next;
    }
    public async Task Invoke(HttpContext context)
    {
        try
        {
            this.BeginInvoke(context);
            await this.next.Invoke(context);
            this.EndInvoke(context);
        }
        catch(Exception ex)
        {
            //Capture the exception.
            string hostName = Environment.MachineName;
            string url = StringFunctions.getCurrentUrl(context);
            string userName = string.Empty;
            string controllerName = string.Empty;
            string actionName = string.Empty;
            //THIS IS NULL BELOW.
            IActionContextAccessor contextAccessor = context.RequestServices.GetService(typeof(IActionContextAccessor)) as IActionContextAccessor;
            RouteData routeData = contextAccessor.ActionContext.RouteData;
            if (context.User != null)
            {
                userName = context.User.Identity.Name;
            }
            if (routeData != null && routeData.Values != null)
            {
                controllerName = routeData.Values["controller"].ToString();
                actionName = routeData.Values["action"].ToString();
            }
            EventLogging.LogApplicationError(hostName, controllerName, actionName, url, userName, ex);
        }
    }
    private void BeginInvoke(HttpContext context)
    {
        //custom work here
    }
    private void EndInvoke(HttpContext context)
    {
        // Do custom work after controller execution
    }
}
 
    Es scheint, dass der 'contextAccessor', von dem ich versuche, die ActionContext.RouteData-Werte abzurufen, Null ist. 
 
    Was mache ich falsch? Vielen Dank.