public override async Task OnResultExecutionAsync(ResultExecutingContext context, ResultExecutionDelegate next)
 {
     if (context.HttpContext.Request.Method == "GET")
     {
         await HandleQueryResponse(context);
     }
     else
     {
         await HandleCommandResponse(context);
     }
     await next();
 }
        public override Task OnResultExecutionAsync(ResultExecutingContext context, ResultExecutionDelegate next)
        {
            var objectResult = context?.Result as ObjectResult;

            if (objectResult != null)
            {
                var queryContext = context.HttpContext.Items[Constants.QueryContextPropertyName] as QueryContext;
                var resourceResult = ResultPreprocessor.PreprocessResult(objectResult.Value, this.Resource, queryContext);

                objectResult.Value = resourceResult;
                objectResult.DeclaredType = typeof(ResourceResult);
            }

            return base.OnResultExecutionAsync(context, next);
        }
Beispiel #3
0
        public async Task ProducesAttribute_SetsContentType()
        {
            // Arrange
            var mediaType1 = MediaTypeHeaderValue.Parse("application/json");
            var mediaType2 = MediaTypeHeaderValue.Parse("text/json;charset=utf-8");
            var producesContentAttribute = new ProducesAttribute("application/json", "text/json;charset=utf-8");
            var resultExecutingContext = CreateResultExecutingContext(new IFilterMetadata[] { producesContentAttribute });
            var next = new ResultExecutionDelegate(
                            () => Task.FromResult(CreateResultExecutedContext(resultExecutingContext)));

            // Act
            await producesContentAttribute.OnResultExecutionAsync(resultExecutingContext, next);

            // Assert
            var objectResult = resultExecutingContext.Result as ObjectResult;
            Assert.Equal(2, objectResult.ContentTypes.Count);
            ValidateMediaType(mediaType1, objectResult.ContentTypes[0]);
            ValidateMediaType(mediaType2, objectResult.ContentTypes[1]);
        }
        public virtual async Task OnResultExecutionAsync(
            ResultExecutingContext context,
            ResultExecutionDelegate next)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            if (next == null)
            {
                throw new ArgumentNullException(nameof(next));
            }

            OnResultExecuting(context);
            if (!context.Cancel)
            {
                OnResultExecuted(await next());
            }
        }
Beispiel #5
0
        /// <inheritdoc />
        public async Task OnResultExecutionAsync(
            ResultExecutingContext context,
            ResultExecutionDelegate next)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            if (next == null)
            {
                throw new ArgumentNullException(nameof(next));
            }

            var controller = context.Controller;
            if (controller == null)
            {
                throw new InvalidOperationException(Resources.FormatPropertyOfTypeCannotBeNull(
                    nameof(context.Controller),
                    nameof(ResultExecutingContext)));
            }

            IAsyncResultFilter asyncResultFilter;
            IResultFilter resultFilter;
            if ((asyncResultFilter = controller as IAsyncResultFilter) != null)
            {
                await asyncResultFilter.OnResultExecutionAsync(context, next);
            }
            else if ((resultFilter = controller as IResultFilter) != null)
            {
                resultFilter.OnResultExecuting(context);
                if (!context.Cancel)
                {
                    resultFilter.OnResultExecuted(await next());
                }
            }
            else
            {
                await next();
            }
        }
Beispiel #6
0
        public async Task ProducesContentAttribute_FormatFilterAttribute_Active()
        {
            // Arrange
            var producesContentAttribute = new ProducesAttribute("application/xml");

            var formatFilter = new Mock<IFormatFilter>();
            formatFilter.Setup(f => f.IsActive)
                .Returns(true);

            var filters = new IFilterMetadata[] { producesContentAttribute, formatFilter.Object };
            var resultExecutingContext = CreateResultExecutingContext(filters);

            var next = new ResultExecutionDelegate(
                            () => Task.FromResult(CreateResultExecutedContext(resultExecutingContext)));

            // Act
            await producesContentAttribute.OnResultExecutionAsync(resultExecutingContext, next);

            // Assert
            var objectResult = Assert.IsType<ObjectResult>(resultExecutingContext.Result);
            Assert.Equal(0, objectResult.ContentTypes.Count);
        }
Beispiel #7
0
        public async Task OnResultExecutionAsync(ResultExecutingContext context, ResultExecutionDelegate next)
        {
            // do something before the action executes
            foreach (var provider in _providers)
            {
                try
                {
                    await provider.OnActionExecutingAsync(context);
                }
                catch (Exception e)
                {
                    if (_logger.IsEnabled(LogLevel.Error))
                    {
                        _logger.LogError(e, e.Message);
                    }
                }
            }

            await next();

            // do something after the action executes; resultContext.Result will be set
            foreach (var provider in _providers)
            {
                try
                {
                    await provider.OnActionExecutedAsync(context);
                }
                catch (Exception e)
                {
                    if (_logger.IsEnabled(LogLevel.Error))
                    {
                        _logger.LogError(e, e.Message);
                    }
                }
            }
        }
Beispiel #8
0
        public override async Task OnResultExecutionAsync(ResultExecutingContext context,
                                                          ResultExecutionDelegate next)
        {
            ObjectResult resultFromAction = context.Result as ObjectResult;

            if (resultFromAction?.Value == null ||
                resultFromAction.StatusCode < 200 ||
                resultFromAction.StatusCode >= 300)
            {
                await next();

                return;
            }

            var(book, bookCovers) = ((Entities.Book, IEnumerable <ExternalModels.BookCover>))resultFromAction.Value;

            var mapper = context.HttpContext.RequestServices.GetRequiredService <IMapper>();

            var mappedBook = mapper.Map <BookWithCovers>(book);

            resultFromAction.Value = mapper.Map(bookCovers, mappedBook);

            await next();
        }
        public override async Task OnResultExecutionAsync(
            ResultExecutingContext context,
            ResultExecutionDelegate next)
        {
            var resultFromAction = context.Result as ObjectResult;

            //If no result value or responses other than 200 statuses
            if (resultFromAction?.Value == null ||
                resultFromAction.StatusCode < 200 ||
                resultFromAction.StatusCode >= 300)
            {
                await next();

                return;
            }

            //Get Automapper services
            var mapper = context.HttpContext.RequestServices.GetRequiredService <IMapper>();

            //Map the result value using Automapper
            resultFromAction.Value = mapper.Map <IEnumerable <Models.Book> >(resultFromAction.Value);

            await next();
        }
        public async Task ProducesContentAttribute_FormatFilterAttribute_Active()
        {
            // Arrange
            var producesContentAttribute = new ProducesAttribute("application/xml");

            var formatFilter = new Mock <IFormatFilter>();

            formatFilter.Setup(f => f.IsActive)
            .Returns(true);

            var filters = new IFilter[] { producesContentAttribute, formatFilter.Object };
            var resultExecutingContext = CreateResultExecutingContext(filters);

            var next = new ResultExecutionDelegate(
                () => Task.FromResult(CreateResultExecutedContext(resultExecutingContext)));

            // Act
            await producesContentAttribute.OnResultExecutionAsync(resultExecutingContext, next);

            // Assert
            var objectResult = Assert.IsType <ObjectResult>(resultExecutingContext.Result);

            Assert.Equal(0, objectResult.ContentTypes.Count);
        }
        // This is used as a 'common' test method for ActionFilterAttribute and ResultFilterAttribute
        public static async Task ResultFilter_SettingCancel_ShortCircuits(Mock mock)
        {
            // Arrange
            mock.As <IAsyncResultFilter>()
            .Setup(f => f.OnResultExecutionAsync(
                       It.IsAny <ResultExecutingContext>(),
                       It.IsAny <ResultExecutionDelegate>()))
            .CallBase();

            mock.As <IResultFilter>()
            .Setup(f => f.OnResultExecuting(It.IsAny <ResultExecutingContext>()))
            .Callback <ResultExecutingContext>(c =>
            {
                mock.ToString();
                c.Cancel = true;
            });

            mock.As <IResultFilter>()
            .Setup(f => f.OnResultExecuted(It.IsAny <ResultExecutedContext>()))
            .Verifiable();

            var context = CreateResultExecutingContext(mock.As <IFilterMetadata>().Object);
            var next    = new ResultExecutionDelegate(() => { throw null; }); // This won't run

            // Act
            await mock.As <IAsyncResultFilter>().Object.OnResultExecutionAsync(context, next);

            // Assert
            Assert.True(context.Cancel);

            mock.As <IResultFilter>()
            .Verify(f => f.OnResultExecuting(It.IsAny <ResultExecutingContext>()), Times.Once());

            mock.As <IResultFilter>()
            .Verify(f => f.OnResultExecuted(It.IsAny <ResultExecutedContext>()), Times.Never());
        }
        public async Task OnResultExecutionAsync(ResultExecutingContext context, ResultExecutionDelegate next)
        {
            // determine the result
            if (context.Result != null)
            {
                // now we need to determine if its a 2xx and change it to a 204
                // or if it's a 4xx and change it to a 404 not found
                if (context.Result is StatusCodeResult statusResult)
                {
                    // todo: log
                    if (statusResult.StatusCode >= (int)HttpStatusCode.OK &&
                        statusResult.StatusCode <= 299)
                    {
                        context.Result = new NoContentResult();
                    }

                    if (statusResult.StatusCode >= (int)HttpStatusCode.BadRequest &&
                        statusResult.StatusCode <= 499)
                    {
                        context.Result = new NotFoundResult();
                    }
                }
                else
                {
                    // todo: log the result
                    context.Result = null;
                }
            }

            if (context.Result == null)
            {
                context.Result = new NoContentResult();
            }

            await next();
        }
Beispiel #13
0
        // This is used as a 'common' test method for ActionFilterAttribute and ResultFilterAttribute
        public static async Task ResultFilter_SettingResult_DoesNotShortCircuit(Mock mock)
        {
            // Arrange
            mock.As <IAsyncResultFilter>()
            .Setup(f => f.OnResultExecutionAsync(
                       It.IsAny <ResultExecutingContext>(),
                       It.IsAny <ResultExecutionDelegate>()))
            .CallBase();

            mock.As <IResultFilter>()
            .Setup(f => f.OnResultExecuting(It.IsAny <ResultExecutingContext>()))
            .Callback <ResultExecutingContext>(c =>
            {
                mock.ToString();
                c.Result = new NoOpResult();
            });

            mock.As <IResultFilter>()
            .Setup(f => f.OnResultExecuted(It.IsAny <ResultExecutedContext>()))
            .Verifiable();

            var context = CreateResultExecutingContext(mock.As <IFilterMetadata>().Object);
            var next    = new ResultExecutionDelegate(() => Task.FromResult(CreateResultExecutedContext(context)));

            // Act
            await mock.As <IAsyncResultFilter>().Object.OnResultExecutionAsync(context, next);

            // Assert
            Assert.False(context.Cancel);

            mock.As <IResultFilter>()
            .Verify(f => f.OnResultExecuting(It.IsAny <ResultExecutingContext>()), Times.Once());

            mock.As <IResultFilter>()
            .Verify(f => f.OnResultExecuted(It.IsAny <ResultExecutedContext>()), Times.Once());
        }
        public async Task OnResultExecutionAsync(ResultExecutingContext context, ResultExecutionDelegate next)
        {
            _logger.LogDebug($"{GetType().Name} in ");
            ControllerActionDescriptor descriptor = context.ActionDescriptor as ControllerActionDescriptor;


            LogEventInfo logEventInfo = new LogEventInfo(LogLevel.Info, _currentLogger.Name,
                                                         $"Custom LogEventInfo, loggerName: {_currentLogger.Name}");

            logEventInfo.Properties["RequestId"]  = context.HttpContext.TraceIdentifier;
            logEventInfo.Properties["IsSuccess"]  = context.HttpContext.Response.StatusCode == (int)HttpStatusCode.OK;
            logEventInfo.Properties["Controller"] = descriptor.ControllerName;
            logEventInfo.Properties["Action"]     = descriptor.ActionName;
            logEventInfo.Properties["Request"]    = null;
            logEventInfo.Properties["Response"]   = JsonConvert.SerializeObject(context.Result);
            logEventInfo.Exception = null;
            _currentLogger.Log(logEventInfo);


            _logger.LogDebug($"{GetType().Name} next ");
            await next();

            _logger.LogDebug($"{GetType().Name} out ");
        }
Beispiel #15
0
        public async Task OnResultExecutionAsync(ResultExecutingContext context, ResultExecutionDelegate next)
        {
            await next();

            //處理成功回傳值
            var controller = (BaseController)context.Controller;

            var result = new
            {
                // 取得由 API 返回的狀態碼
                Status = controller.Status,

                // 取得由 API 返回的 Result Code
                Result = controller.Result,

                // 取得由 API 返回的資料
                data = controller.Data,

                // 取得由 API 返回的處理訊息
                Message = controller.Message
            };


            var json = JsonConvert.SerializeObject(result, Formatting.None);

            var bytes  = Encoding.UTF8.GetBytes(json);
            int length = bytes.Length;

            var response = context.HttpContext.Response;

            //this must be set before start writing into the stream
            response.ContentLength = length;
            response.ContentType   = "application/json";

            await response.Body.WriteAsync(bytes, 0, length);
        }
Beispiel #16
0
 public async Task OnResultExecutionAsync(ResultExecutingContext context, ResultExecutionDelegate next)
 {
     if (context.Result is EmptyResult)
     {
         context.Result = new ObjectResult(ResultInfo.Create());
     }
     else if (context.Result is ObjectResult objectResult)
     {
         if (objectResult.Value is ResultInfo resultInfo)
         {
             context.Result = new ObjectResult(resultInfo);
         }
         else
         {
             objectResult.StatusCode ??= 200;
             context.Result = new ObjectResult(ResultInfo.Create(
                                                   (StatusCode)objectResult.StatusCode,
                                                   objectResult.StatusCode == 200 ? "Success" : context.Result.GetType().Name.Replace("ObjectResult", ""),
                                                   objectResult.Value)
                                               );
         }
     }
     _ = await next();
 }
        public async Task OnResultExecutionAsync(ResultExecutingContext context,
                                                 ResultExecutionDelegate next)
        {
            if (context.HttpContext.User.Identity.IsAuthenticated)
            {
                var controllerActionDescriptor
                    = context.ActionDescriptor as ControllerActionDescriptor;
                if (!controllerActionDescriptor.ControllerTypeInfo
                    .IsDefined(typeof(Attributes.SuppressNotifications)) &&
                    !controllerActionDescriptor.MethodInfo
                    .IsDefined(typeof(Attributes.SuppressNotifications)))
                {
                    var notifications = await _userService.GetNotificationsForUser();

                    if (notifications.Any())
                    {
                        context.HttpContext.Items[ItemKey.NotificationsList] = notifications;
                    }

                    await next();

                    if (context.HttpContext.Items[ItemKey.NotificationsDisplayed] as bool? == true)
                    {
                        await _userService.ClearNotificationsForUser();
                    }
                }
                else
                {
                    await next();
                }
            }
            else
            {
                await next();
            }
        }
        public async Task OnResultExecutionAsync(ResultExecutingContext context, ResultExecutionDelegate next)
        {
            // Should only run on the front-end for a full view
            if ((context.Result is ViewResult || context.Result is PageResult) &&
                !AdminAttribute.IsApplied(context.HttpContext))
            {
                if (_scriptsCache == null)
                {
                    var settings = (await _siteService.GetSiteSettingsAsync()).As <MatomoSettings>();

                    if (!string.IsNullOrWhiteSpace(settings?.SiteID) && !string.IsNullOrWhiteSpace(settings?.ServerUri))
                    {
                        _scriptsCache = new HtmlString($"<script>var _paq = window._paq || [];_paq.push(['trackPageView']);_paq.push(['enableLinkTracking']);_paq.push(['setTrackerUrl', 'https://{settings.ServerUri}/matomo.php']);_paq.push(['setSiteId', '{settings.SiteID}']);</script> <script src=\"https://{settings.ServerUri}/matomo.js\" async defer></script> ");
                    }
                }

                if (_scriptsCache != null)
                {
                    _resourceManager.RegisterHeadScript(_scriptsCache);
                }
            }

            await next.Invoke();
        }
Beispiel #19
0
        public async Task OnResultExecutionAsync(ResultExecutingContext context, ResultExecutionDelegate next)
        {
            // Should only run on the front-end for a full view
            if ((context.Result is ViewResult || context.Result is PageResult) &&
                !AdminAttribute.IsApplied(context.HttpContext))
            {
                if (_scriptsCache == null)
                {
                    var settings = (await _siteService.GetSiteSettingsAsync()).As <GoogleAdSenseSettings>();

                    if (!string.IsNullOrWhiteSpace(settings?.PublisherID))
                    {
                        _scriptsCache = new HtmlString($"\n<script async src=\"https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js\"></script>");
                    }
                }

                if (_scriptsCache != null)
                {
                    _resourceManager.RegisterHeadScript(_scriptsCache);
                }
            }

            await next.Invoke();
        }
Beispiel #20
0
        public override Task OnResultExecutionAsync(ResultExecutingContext context, ResultExecutionDelegate next)
        {
            if (context.ModelState.IsValid)
            {
                return(base.OnResultExecutionAsync(context, next));
            }

            if (context.ModelState.Keys.Any())
            {
                Dictionary <string, string[]> errors = context
                                                       .ModelState
                                                       .ToDictionary(kvp => kvp.Key, kvp => kvp.Value.Errors.Select(e => e.ErrorMessage).ToArray());

                var resultContent = ResultContent <string> .Failure(HttpStatusCode.BadRequest, "Validation Errors", errors);

                context.Result = new BadRequestObjectResult(resultContent);
            }
            else
            {
                context.Result = new BadRequestObjectResult(context.ModelState);
            }

            return(base.OnResultExecutionAsync(context, next));
        }
        /// <inheritdoc />
        public Task OnResultExecutionAsync(
            ResultExecutingContext context,
            ResultExecutionDelegate next)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            if (next == null)
            {
                throw new ArgumentNullException(nameof(next));
            }

            var controller = context.Controller;

            if (controller == null)
            {
                throw new InvalidOperationException(Resources.FormatPropertyOfTypeCannotBeNull(
                                                        nameof(context.Controller),
                                                        nameof(ResultExecutingContext)));
            }

            if (controller is IAsyncResultFilter asyncResultFilter)
            {
                return(asyncResultFilter.OnResultExecutionAsync(context, next));
            }
            else if (controller is IResultFilter resultFilter)
            {
                return(ExecuteResultFilter(context, next, resultFilter));
            }
            else
            {
                return(next());
            }
        }
        public async Task OnResultExecutionAsync(ResultExecutingContext context, ResultExecutionDelegate next)
        {
            var apiResponse = ApiResponseContract.From(_notificationContext.Notifications);

            if ((context.Result is OkObjectResult ||
                 context.Result is NoContentResult ||
                 context.Result is CreatedResult) &&
                !apiResponse.Success)
            {
                var json = JsonConvert.SerializeObject(apiResponse.ToJson(), new JsonSerializerSettings
                {
                    ContractResolver = new CamelCasePropertyNamesContractResolver()
                });

                context.HttpContext.Response.StatusCode  = StatusCodes.Status400BadRequest;
                context.HttpContext.Response.ContentType = "application/json";
                await context.HttpContext.Response.WriteAsync(json);
            }

            if (!context.HttpContext.Response.HasStarted)
            {
                await next();
            }
        }
Beispiel #23
0
            public async Task OnResultExecutionAsync(ResultExecutingContext context, ResultExecutionDelegate next)
            {
                // do something before the action executes
                await next();

                //after the action executes
                var timingSession = ProfilingSession.Current.Profiler.GetTimingSession();

                if (timingSession != null)
                {
                    string sessionId = timingSession.Id.ToString();
                    List <CoreProfilerModulecs> coreProfilerModulecs = new List <CoreProfilerModulecs>();
                    foreach (var timing in timingSession.Timings)
                    {
                        long duration = 0;
                        if (timing.Name.ToLowerInvariant() == "root" && timing.DurationMilliseconds <= 0)
                        {
                            duration = timingSession.DurationMilliseconds;
                        }
                        coreProfilerModulecs.Add(new CoreProfilerModulecs
                        {
                            SessionId = sessionId,
                            ParentId  = timing.ParentId.HasValue ? timing.ParentId.Value.ToString() : "",
                            Machine   = timingSession.MachineName,
                            Type      = timing.Type,
                            CurrentId = timing.Id.ToString(),
                            Name      = timing.Name,
                            Start     = timing.StartMilliseconds,
                            Duration  = duration > 0 ? duration : timing.DurationMilliseconds,
                            Sort      = timing.Sort,
                            Started   = timing.Started
                        });
                    }
                    await _coreProfilerRepository.BulkInsertAsync(coreProfilerModulecs);
                }
            }
Beispiel #24
0
        public override async Task OnResultExecutionAsync(ResultExecutingContext context, ResultExecutionDelegate next)
        {
            if (Configuration.AuditDisabled || IsActionIgnored(context.ActionDescriptor))
            {
                await next.Invoke();

                return;
            }
            var resultExecutionContext = await next.Invoke();

            await AfterResultAsync(resultExecutionContext);
        }
        public override async Task OnResultExecutionAsync(ResultExecutingContext context, ResultExecutionDelegate next)
        {
            var resultFromAction = context.Result as ObjectResult;

            if (resultFromAction?.Value == null ||
                resultFromAction.StatusCode < 200 ||
                resultFromAction.StatusCode >= 300)
            {
                await next();

                return;
            }

            //var (book, bookCovers) =
            //    ((Entities.Book book, IEnumerable<ExternalModels.BookCover> bookCovers))resultFromAction.Value;
            // // to check if we can simplify naming
            //var temp = ((Entities.Book, IEnumerable<ExternalModels.BookCover>)) resultFromAction.Value;

            var(book, bookCovers) =
                ((Entities.Book, IEnumerable <ExternalModels.BookCover>))resultFromAction.Value;


            // this means we can simplify names in BooksController

            var mappedBook = Mapper.Map <BookWithCovers>(book);

            resultFromAction.Value = Mapper.Map(bookCovers, mappedBook);

            await next();
        }
Beispiel #26
0
        /// <summary>
        /// 执行生成
        /// </summary>
        public override async Task OnResultExecutionAsync(ResultExecutingContext context, ResultExecutionDelegate next)
        {
            await WriteViewToFileAsync(context);

            await base.OnResultExecutionAsync(context, next);
        }
Beispiel #27
0
        public async Task OnResultExecutionAsync(ResultExecutingContext filterContext, ResultExecutionDelegate next)
        {
            // Should only run on a full view rendering result
            if (!(filterContext.Result is ViewResult))
            {
                await next();

                return;
            }

            // Should only run on the Admin
            if (!AdminAttribute.IsApplied(filterContext.HttpContext))
            {
                await next();

                return;
            }

            // Should only run for authenticated users
            if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
            {
                await next();

                return;
            }

            // Don't create the menu if the status code is 3xx
            var statusCode = filterContext.HttpContext.Response.StatusCode;

            if (statusCode >= 300 && statusCode < 400)
            {
                await next();

                return;
            }

            // Populate main nav
            var menuShape = await _shapeFactory.CreateAsync("Navigation",
                                                            Arguments.From(new
            {
                MenuName  = "admin",
                RouteData = filterContext.RouteData,
            }));

            dynamic layout = await _layoutAccessor.GetLayoutAsync();

            layout.Navigation.Add(menuShape);

            await next();
        }
Beispiel #28
0
        public override async Task OnResultExecutionAsync(ResultExecutingContext context, ResultExecutionDelegate next)
        {
            if (context.HttpContext.Request.Cookies.ContainsKey(CookieNames.SeenOutageMessage) == false)
            {
                if (string.IsNullOrEmpty(_systemConfig.PlannedOutageMessage) == false)
                {
                    var ctrlr = (Controller)context.Controller;
                    ctrlr.ViewData.Add(ViewDataKeys.CanShowOutageMessage, true);
                    ctrlr.ViewData.Add(ViewDataKeys.PlannedOutageMessage, _systemConfig.PlannedOutageMessage);
                }
            }

            await next();
        }
Beispiel #29
0
 public override Task OnResultExecutionAsync(ResultExecutingContext context, ResultExecutionDelegate next)
 {
     return(base.OnResultExecutionAsync(context, next));
 }
Beispiel #30
0
        public override async Task OnResultExecutionAsync(ResultExecutingContext context, ResultExecutionDelegate next)
        {
            var resultFromAction = context.Result as ObjectResult;

            if (resultFromAction?.Value == null || resultFromAction.StatusCode < 200 || resultFromAction.StatusCode >= 300)
            {
                await next();

                return;
            }

            resultFromAction.Value = Mapper.Map <IEnumerable <ViewModels.CustomerView> >(resultFromAction.Value);

            await next();
        }
Beispiel #31
0
        public async Task OnResultExecutionAsync(ResultExecutingContext context, ResultExecutionDelegate next)
        {
            // Should only run on the front-end for a full view
            if ((context.Result is ViewResult || context.Result is PageResult) &&
                !AdminAttribute.IsApplied(context.HttpContext))
            {
                // Even if the Admin attribute is not applied we might be using the admin theme, for instance in Login views.
                // In this case don't render Layers.
                var selectedTheme = (await _themeManager.GetThemeAsync())?.Id;
                var adminTheme    = await _adminThemeService.GetAdminThemeNameAsync();

                if (selectedTheme == adminTheme)
                {
                    await next.Invoke();

                    return;
                }

                var widgets = await _memoryCache.GetOrCreateAsync("OrchardCore.Layers.LayerFilter:AllWidgets", entry =>
                {
                    entry.AddExpirationToken(_signal.GetToken(LayerMetadataHandler.LayerChangeToken));
                    return(_layerService.GetLayerWidgetsAsync(x => x.Published));
                });

                var layers = (await _layerService.GetLayersAsync()).Layers.ToDictionary(x => x.Name);

                dynamic layout = await _layoutAccessor.GetLayoutAsync();

                var updater = _modelUpdaterAccessor.ModelUpdater;

                var engine = _scriptingManager.GetScriptingEngine("js");
                var scope  = engine.CreateScope(_scriptingManager.GlobalMethodProviders.SelectMany(x => x.GetMethods()), _serviceProvider, null, null);

                var layersCache = new Dictionary <string, bool>();

                foreach (var widget in widgets)
                {
                    var layer = layers[widget.Layer];

                    if (layer == null)
                    {
                        continue;
                    }

                    bool display;
                    if (!layersCache.TryGetValue(layer.Name, out display))
                    {
                        if (String.IsNullOrEmpty(layer.Rule))
                        {
                            display = false;
                        }
                        else
                        {
                            display = Convert.ToBoolean(engine.Evaluate(scope, layer.Rule));
                        }

                        layersCache[layer.Rule] = display;
                    }

                    if (!display)
                    {
                        continue;
                    }

                    var widgetContent = await _contentItemDisplayManager.BuildDisplayAsync(widget.ContentItem, updater);

                    widgetContent.Classes.Add("widget");
                    widgetContent.Classes.Add("widget-" + widget.ContentItem.ContentType.HtmlClassify());

                    var wrapper = new WidgetWrapper
                    {
                        Widget  = widget.ContentItem,
                        Content = widgetContent
                    };

                    wrapper.Metadata.Alternates.Add("Widget_Wrapper__" + widget.ContentItem.ContentType);
                    wrapper.Metadata.Alternates.Add("Widget_Wrapper__Zone__" + widget.Zone);

                    var contentZone = layout.Zones[widget.Zone];
                    contentZone.Add(wrapper);
                }
            }

            await next.Invoke();
        }
Beispiel #32
0
        public override async Task OnResultExecutionAsync(ResultExecutingContext context, ResultExecutionDelegate next)
        {
            //  return base.OnResultExecutionAsync(context, next);

            var resultFromAction = context.Result as ObjectResult;

            if (resultFromAction?.Value == null ||
                resultFromAction.StatusCode < 200 ||
                resultFromAction.StatusCode >= 300)
            {
                await next();

                return;
            }

            resultFromAction.Value = AutoMapper.Mapper.Map <IEnumerable <Models.Book> >(resultFromAction.Value);

            await next();
        }
Beispiel #33
0
 /// <summary>
 /// 执行后
 /// </summary>
 /// <param name="context"></param>
 /// <param name="next"></param>
 /// <returns></returns>
 public override async Task OnResultExecutionAsync(ResultExecutingContext context, ResultExecutionDelegate next)
 {
     //if (context.HttpContext.Response.StatusCode == 404)
     //{
     //    context.HttpContext.Response.Redirect("login/InternalError");
     //}
     await base.OnResultExecutionAsync(context, next);
 }
        public override async Task OnResultExecutionAsync(ResultExecutingContext context, ResultExecutionDelegate next)
        {
            //TODO: invalidate cache, this is inefficient
            var robots = await _robotService.GetRobotsBy(string.Empty, null);

            _helpersManager.Cache.Set((DateTime.Today, ActorType.Robot), robots.Select(e => new RobotViewModel(e)).ToArray());
            await next();
        }
        public override async Task OnResultExecutionAsync(ResultExecutingContext context, ResultExecutionDelegate next)
        {
            var result = context.Result as ObjectResult;

            if (result.Value == null ||
                result.StatusCode < 200 ||
                result.StatusCode >= 300)
            {
                await next();

                return;
            }

            result.Value = new PersonReplyDto().CopyPropertiesFrom(result.Value);
            await next();
        }
        public override async Task OnResultExecutionAsync(ResultExecutingContext context, ResultExecutionDelegate next)
        {
            try
            {
                if (_resultProvider.HasAnyPolicy(context.Result, out ObjectResult result))
                {
                    var finalResult = await _resultProvider.GetContentResultAsync(result).ConfigureAwait(false);

                    if (finalResult != null)
                    {
                        context.Result = finalResult;
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.LogWarning(ex, "Something went wrong while processing link generation.");
            }

            await base.OnResultExecutionAsync(context, next).ConfigureAwait(false);
        }
        // This is used as a 'common' test method for ActionFilterAttribute and ResultFilterAttribute
        public static async Task ResultFilter_Calls_OnResultExecuted(Mock mock)
        {
            // Arrange
            mock.As<IAsyncResultFilter>()
                .Setup(f => f.OnResultExecutionAsync(
                    It.IsAny<ResultExecutingContext>(),
                    It.IsAny<ResultExecutionDelegate>()))
                .CallBase();

            mock.As<IResultFilter>()
                .Setup(f => f.OnResultExecuting(It.IsAny<ResultExecutingContext>()))
                .Verifiable();

            mock.As<IResultFilter>()
                .Setup(f => f.OnResultExecuted(It.IsAny<ResultExecutedContext>()))
                .Verifiable();

            var context = CreateResultExecutingContext(mock.As<IFilter>().Object);
            var next = new ResultExecutionDelegate(() => Task.FromResult(CreateResultExecutedContext(context)));

            // Act
            await mock.As<IAsyncResultFilter>().Object.OnResultExecutionAsync(context, next);

            // Assert
            Assert.False(context.Cancel);

            mock.As<IResultFilter>()
                .Verify(f => f.OnResultExecuting(It.IsAny<ResultExecutingContext>()), Times.Once());

            mock.As<IResultFilter>()
                .Verify(f => f.OnResultExecuted(It.IsAny<ResultExecutedContext>()), Times.Once());
        }
        // This is used as a 'common' test method for ActionFilterAttribute and ResultFilterAttribute
        public static async Task ResultFilter_SettingCancel_ShortCircuits(Mock mock)
        {
            // Arrange
            mock.As<IAsyncResultFilter>()
                .Setup(f => f.OnResultExecutionAsync(
                    It.IsAny<ResultExecutingContext>(),
                    It.IsAny<ResultExecutionDelegate>()))
                .CallBase();

            mock.As<IResultFilter>()
                .Setup(f => f.OnResultExecuting(It.IsAny<ResultExecutingContext>()))
                .Callback<ResultExecutingContext>(c =>
                {
                    mock.ToString();
                    c.Cancel = true;
                });

            mock.As<IResultFilter>()
                .Setup(f => f.OnResultExecuted(It.IsAny<ResultExecutedContext>()))
                .Verifiable();

            var context = CreateResultExecutingContext(mock.As<IFilter>().Object);
            var next = new ResultExecutionDelegate(() => { throw null; }); // This won't run

            // Act
            await mock.As<IAsyncResultFilter>().Object.OnResultExecutionAsync(context, next);

            // Assert
            Assert.True(context.Cancel);

            mock.As<IResultFilter>()
                .Verify(f => f.OnResultExecuting(It.IsAny<ResultExecutingContext>()), Times.Once());

            mock.As<IResultFilter>()
                .Verify(f => f.OnResultExecuted(It.IsAny<ResultExecutedContext>()), Times.Never());
        }
        // This is used as a 'common' test method for ActionFilterAttribute and ResultFilterAttribute
        public static async Task ResultFilter_SettingResult_DoesNotShortCircuit(Mock mock)
        {
            // Arrange
            mock.As<IAsyncResultFilter>()
                .Setup(f => f.OnResultExecutionAsync(
                    It.IsAny<ResultExecutingContext>(),
                    It.IsAny<ResultExecutionDelegate>()))
                .CallBase();

            mock.As<IResultFilter>()
                .Setup(f => f.OnResultExecuting(It.IsAny<ResultExecutingContext>()))
                .Callback<ResultExecutingContext>(c =>
                {
                    mock.ToString();
                    c.Result = new NoOpResult();
                });

            mock.As<IResultFilter>()
                .Setup(f => f.OnResultExecuted(It.IsAny<ResultExecutedContext>()))
                .Verifiable();

            var context = CreateResultExecutingContext(mock.As<IFilter>().Object);
            var next = new ResultExecutionDelegate(() => Task.FromResult(CreateResultExecutedContext(context)));

            // Act
            await mock.As<IAsyncResultFilter>().Object.OnResultExecutionAsync(context, next);

            // Assert
            Assert.False(context.Cancel);

            mock.As<IResultFilter>()
                .Verify(f => f.OnResultExecuting(It.IsAny<ResultExecutingContext>()), Times.Once());

            mock.As<IResultFilter>()
                .Verify(f => f.OnResultExecuted(It.IsAny<ResultExecutedContext>()), Times.Once());
        }