Beispiel #1
0
        public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            IFeatureManager featureManager = context.HttpContext.RequestServices.GetRequiredService <IFeatureManagerSnapshot>();

            if (await featureManager.IsEnabledAsync(FeatureName).ConfigureAwait(false))
            {
                var serviceProvider = context.HttpContext.RequestServices.GetRequiredService <IServiceProvider>();

                IAsyncActionFilter filter = ActivatorUtilities.CreateInstance <T>(serviceProvider);

                await filter.OnActionExecutionAsync(context, next).ConfigureAwait(false);
            }
            else
            {
                await next().ConfigureAwait(false);
            }
        }
        public async Task OnActionExecutionAsyncMethodHappyPath2()
        {
            const string   messageFormat          = "My message format: {0}";
            const LogLevel logLevel               = LogLevel.Info;
            const string   exceptionMessageFormat = "My exception message format: {0}.";
            const LogLevel exceptionLogLevel      = LogLevel.Fatal;
            const string   actionName             = "MyAction";
            const string   actionArgumentName     = "foo";
            const int      actionArgument         = 123;

            var mockActionFilter = new Mock <LoggingActionFilter>(messageFormat, null, logLevel);

            mockActionFilter.Object.ExceptionMessageFormat = exceptionMessageFormat;
            mockActionFilter.Object.ExceptionLogLevel      = exceptionLogLevel;

            IAsyncActionFilter loggingActionFilter = mockActionFilter.Object;

            var mockLogger = new MockLogger();

            var httpContext = new DefaultHttpContext()
            {
                RequestServices = GetServiceProvider(mockLogger.Object)
            };
            var actionContext = new ActionContext(httpContext, new RouteData(), new ActionDescriptor()
            {
                DisplayName = actionName
            });
            var context = new ActionExecutingContext(actionContext, Array.Empty <IFilterMetadata>(), new Dictionary <string, object>(), null);

            context.ActionArguments.Add(actionArgumentName, actionArgument);

            var actionExecutedContext = new ActionExecutedContext(actionContext, Array.Empty <IFilterMetadata>(), null);
            var exception             = actionExecutedContext.Exception = new Exception();

            ActionExecutionDelegate next = () => Task.FromResult(actionExecutedContext);

            await loggingActionFilter.OnActionExecutionAsync(context, next);

            mockLogger.VerifyFatal(string.Format(exceptionMessageFormat, actionName), exception,
                                   new { foo = 123, ResponseStatusCode = 500 }, Times.Once());
        }