public void OnPageHandlerExecuted_IfResultIsRedirectToPageResult_ExpectItemInTempData()
        {
            var tempDataDictionary = new Mock <ITempDataDictionary>();

            tempDataDictionary.Setup(x => x[It.IsAny <string>()])
            .Callback((string key) =>
            {
                Assert.Equal("NotificationPageModelPageNotifications", key);
            });

            var page = new TestableNotificationPageModel {
                TempData = tempDataDictionary.Object
            };

            var pageContext = new PageContext(new ActionContext(
                                                  new DefaultHttpContext(),
                                                  new RouteData(),
                                                  new PageActionDescriptor(),
                                                  new ModelStateDictionary()));

            var pageHandlerExecutedContext = new PageHandlerExecutedContext(
                pageContext,
                Array.Empty <IFilterMetadata>(),
                new HandlerMethodDescriptor(),
                page)
            {
                Result = new RedirectToPageResult("page-name")
            };

            page.AddNotification();
            page.OnPageHandlerExecuted(pageHandlerExecutedContext);
        }
        public void OnPageHandlerExecuted_GivenResultIsNotRedirectToPageResult_ExpectNoItemInTempData()
        {
            var pageContext = new PageContext(new ActionContext(
                                                  new DefaultHttpContext(),
                                                  new RouteData(),
                                                  new PageActionDescriptor(),
                                                  new ModelStateDictionary()));

            var model = new Mock <PageModel>();

            var pageHandlerExecutedContext = new PageHandlerExecutedContext(
                pageContext,
                Array.Empty <IFilterMetadata>(),
                new HandlerMethodDescriptor(),
                model.Object)
            {
                Result = new PageResult()
            };

            var page = new TestableNotificationPageModel();

            page.OnPageHandlerExecuted(pageHandlerExecutedContext);

            Assert.Null(page.TempData);
        }
示例#3
0
        protected virtual async Task HandleAndWrapException(PageHandlerExecutedContext context)
        {
            //TODO: Trigger an AbpExceptionHandled event or something like that.

            context.HttpContext.Response.Headers.Add(AbpHttpConsts.AbpErrorFormat, "true");
            context.HttpContext.Response.StatusCode = (int)context
                                                      .GetRequiredService <IHttpExceptionStatusCodeFinder>()
                                                      .GetStatusCode(context.HttpContext, context.Exception);

            var exceptionHandlingOptions      = context.GetRequiredService <IOptions <AbpExceptionHandlingOptions> >().Value;
            var exceptionToErrorInfoConverter = context.GetRequiredService <IExceptionToErrorInfoConverter>();
            var remoteServiceErrorInfo        = exceptionToErrorInfoConverter.Convert(context.Exception, exceptionHandlingOptions.SendExceptionsDetailsToClients);

            context.Result = new ObjectResult(new RemoteServiceErrorResponse(remoteServiceErrorInfo));

            var logLevel = context.Exception.GetLogLevel();

            var remoteServiceErrorInfoBuilder = new StringBuilder();

            remoteServiceErrorInfoBuilder.AppendLine($"---------- {nameof(RemoteServiceErrorInfo)} ----------");
            remoteServiceErrorInfoBuilder.AppendLine(context.GetRequiredService <IJsonSerializer>().Serialize(remoteServiceErrorInfo, indented: true));

            var logger = context.GetService <ILogger <AbpExceptionFilter> >(NullLogger <AbpExceptionFilter> .Instance);

            logger.LogWithLevel(logLevel, remoteServiceErrorInfoBuilder.ToString());

            logger.LogException(context.Exception, logLevel);

            await context.GetRequiredService <IExceptionNotifier>().NotifyAsync(new ExceptionNotificationContext(context.Exception));

            context.Exception = null; //Handled!
        }
示例#4
0
        public void OnPageHandlerExecuted(PageHandlerExecutedContext context)
        {
            var result = context.Result;

            if (result is PageResult pageResult)
            {
                var viewData = pageResult.ViewData;

                if (!this._memoryCache.TryGetValue(GlobalConstants.ApplicationInfo, out ContactInfoViewModel model))
                {
                    model = new ContactInfoViewModel()
                    {
                        AppName = this._settingsService.Get(GlobalConstants.ApplicationNameKey),
                        AppFooterAboutContent = this._settingsService.Get(GlobalConstants.ApplicationAboutFooterKey),
                        AppAddress            = this._settingsService.Get(GlobalConstants.ApplicationAddressKey),
                        AppEmail = this._settingsService.Get(GlobalConstants.ApplicationEmailKey),
                        AppPhone = this._settingsService.Get(GlobalConstants.ApplicationPhoneKey)
                    };

                    var cacheOption = new MemoryCacheEntryOptions()
                                      .SetAbsoluteExpiration(TimeSpan.FromHours(GlobalConstants.ApplicationInfoCacheExpirationDay));

                    this._memoryCache.Set(GlobalConstants.ApplicationInfoCacheExpirationDay, model, cacheOption);
                }

                viewData[GlobalConstants.ApplicationInfo] = model;
            }
        }
 public void OnPageHandlerExecuted(PageHandlerExecutedContext context)
 {
     if (context.HttpContext.User.Identity.IsAuthenticated)
     {
         context.Result = new RedirectResult("/Home");
     }
 }
示例#6
0
            public async Task VerifyAsyncReturnsBoolean(bool success)
            {
                var reCaptchaServiceMock = new Mock <IReCaptchaService>();

                reCaptchaServiceMock.Setup(x => x.VerifyAsync(It.IsAny <string>())).Returns(Task.FromResult(success));

                var filter = new ValidateRecaptchaFilter(reCaptchaServiceMock.Object, "", "");

                var expected = new StringValues("123");

                var httpContextMock = new Mock <HttpContext>();

                var pageContext = CreatePageContext(new ActionContext(httpContextMock.Object, new RouteData(), new ActionDescriptor()));

                var model = new Mock <PageModel>();

                var pageHandlerExecutedContext = new PageHandlerExecutedContext(
                    pageContext,
                    Array.Empty <IFilterMetadata>(),
                    new HandlerMethodDescriptor(),
                    model.Object);

                var actionExecutingContext = CreatePageHandlerExecutingContext(httpContextMock, pageContext, expected, model);

                PageHandlerExecutionDelegate next = () => Task.FromResult(pageHandlerExecutedContext);

                await filter.OnPageHandlerExecutionAsync(actionExecutingContext, next);

                reCaptchaServiceMock.Verify(x => x.VerifyAsync(It.IsAny <string>()), Times.Once);
            }
        public void OnPageHandlerExecuted(PageHandlerExecutedContext context)
        {
            var log = "executed";

            context.HttpContext.Response.Headers.Add(
                "X-Developer", new StringValues("Tahir"));
        }
示例#8
0
        protected virtual int GetStatusCode(PageHandlerExecutedContext context, bool wrapOnError)
        {
            if (context.Exception is AbpAuthorizationException)
            {
                return(context.HttpContext.User.Identity.IsAuthenticated
                    ? (int)HttpStatusCode.Forbidden
                    : (int)HttpStatusCode.Unauthorized);
            }

            if (context.Exception is AbpValidationException)
            {
                return((int)HttpStatusCode.BadRequest);
            }

            if (context.Exception is EntityNotFoundException)
            {
                return((int)HttpStatusCode.NotFound);
            }

            if (wrapOnError)
            {
                return((int)HttpStatusCode.InternalServerError);
            }

            return(context.HttpContext.Response.StatusCode);
        }
        public void OnPageHandlerExecuted(PageHandlerExecutedContext context)
        {
            var log = "executed";

            context.HttpContext.Response.Headers.Add(
                "X-Greeting", new StringValues(this.greetingService.Greet("Tahir")));
        }
示例#10
0
        protected virtual void HandleAndWrapException(PageHandlerExecutedContext context, WrapResultAttribute wrapResultAttribute)
        {
            if (!ActionResultHelper.IsObjectResult(context.HandlerMethod.MethodInfo.ReturnType))
            {
                return;
            }

            context.HttpContext.Response.StatusCode = GetStatusCode(context, wrapResultAttribute.WrapOnError);

            if (!wrapResultAttribute.WrapOnError)
            {
                return;
            }

            context.Result = new ObjectResult(
                new AjaxResponse(
                    _errorInfoBuilder.BuildForException(context.Exception),
                    context.Exception is AbpAuthorizationException
                    )
                );

            EventBus.Trigger(this, new AbpHandledExceptionData(context.Exception));

            context.Exception = null; //Handled!
        }
示例#11
0
        protected virtual async Task HandleAndWrapException(PageHandlerExecutedContext context)
        {
            //TODO: Trigger an PlusExceptionHandled event or something like that.

            context.HttpContext.Response.Headers.Add(PlusHttpConsts.PlusErrorFormat, "true");
            context.HttpContext.Response.StatusCode = (int)_statusCodeFinder.GetStatusCode(context.HttpContext, context.Exception);

            var remoteServiceErrorInfo = _errorInfoConverter.Convert(context.Exception);

            context.Result = new ObjectResult(new RemoteServiceErrorResponse(remoteServiceErrorInfo));

            var logLevel = context.Exception.GetLogLevel();

            Logger.LogWithLevel(logLevel, $"---------- {nameof(RemoteServiceErrorInfo)} ----------");
            Logger.LogWithLevel(logLevel, _jsonSerializer.Serialize(remoteServiceErrorInfo, indented: true));
            Logger.LogException(context.Exception, logLevel);

            await context.HttpContext
            .RequestServices
            .GetRequiredService <IExceptionNotifier>()
            .NotifyAsync(
                new ExceptionNotificationContext(context.Exception)
                );

            context.Exception = null; //Handled!
        }
示例#12
0
        protected virtual void HandleAndWrapException(PageHandlerExecutedContext context,
                                                      WrapResultAttribute wrapResultAttribute)
        {
            if (!ActionResultHelper.IsObjectResult(context.HandlerMethod.MethodInfo.ReturnType))
            {
                return;
            }

            var displayUrl = context.HttpContext.Request.GetDisplayUrl();

            if (_abpWebCommonModuleConfiguration.WrapResultFilters.HasFilterForWrapOnError(displayUrl,
                                                                                           out var wrapOnError))
            {
                context.HttpContext.Response.StatusCode = GetStatusCode(context, wrapOnError);

                if (!wrapOnError)
                {
                    return;
                }

                HandleError(context);
                return;
            }

            context.HttpContext.Response.StatusCode = GetStatusCode(context, wrapResultAttribute.WrapOnError);

            if (!wrapResultAttribute.WrapOnError)
            {
                return;
            }

            HandleError(context);
        }
 public void OnPageHandlerExecuted(PageHandlerExecutedContext ctx)
 {
     // Example requested in comments on answer.
     if (ctx.Result is PageResult pageResult)
     {
         pageResult.ViewData["Property"] = "Value";
     }
 }
 public override void OnPageHandlerExecuted(PageHandlerExecutedContext context)
 {
     if (!CheckToken(context.HttpContext))
     {
         context.Result = RedirectToPage("/Login");
     }
     base.OnPageHandlerExecuted(context);
 }
示例#15
0
        public void OnPageHandlerExecuted(PageHandlerExecutedContext context)
        {
            var attrs = GetAttrs(context);

            foreach (var attr in attrs)
            {
                attr.OnPageHandlerExecuted(context);
            }
        }
 public void OnPageHandlerExecuted(PageHandlerExecutedContext context)
 {
     // This usage mimics Identity UI where it sets data into ViewData in a PageFilters's
     // PageHandlerExecuted method.
     if (context.Result is PageResult pageResult)
     {
         pageResult.ViewData["Foo"] = "Bar";
     }
 }
示例#17
0
 public override void OnPageHandlerExecuted(PageHandlerExecutedContext context)
 {
     base.OnPageHandlerExecuted(context);
     if (context.Result is RedirectToPageResult)
     {
         var pageNotifications = JsonConvert.SerializeObject(this._pageNotifications);
         this.TempData[$"{Key}PageNotifications"] = pageNotifications;
     }
 }
        public void OnPageHandlerExecuted(PageHandlerExecutedContext context)
        {
            var name = context.HandlerMethod?.Name ?? context.HandlerMethod?.MethodInfo.Name;

            if (name != null)
            {
                _diagnosticContext.Set("RazorPageHandler", name);
            }
        }
 public override void OnPageHandlerExecuted(PageHandlerExecutedContext context)
 {
     Console.WriteLine($"Executing Index.OnPageHandlerExecuted: cancelled {context.Canceled}");
     //executedContext.ExceptionHandled = true;
     //executedContext.Result = new ContentResult()
     //{
     //    Content = "GlobalLogAsyncPageFilter - convert to success ",
     //};
 }
示例#20
0
        public void OnPageHandlerExecuted(PageHandlerExecutedContext pageContext)
        {
            var result = pageContext.Result;

            if (result is PageResult)
            {
                var page = ((PageResult)result);
                page.ViewData["CompanyName"] = companyName;
            }
        }
示例#21
0
        public override void OnPageHandlerExecuted(PageHandlerExecutedContext context)
        {
            _timer.Stop();
            _logger.LogRoutePerformance(context.ActionDescriptor.RelativePath,
                                        context.HttpContext.Request.Method,
                                        _timer.ElapsedMilliseconds);

            _userScope?.Dispose();
            _hostScope?.Dispose();
        }
示例#22
0
        public void OnPageHandlerExecuted(PageHandlerExecutedContext context)
        {
            var method = context.HttpContext.Request.Method;
            var action = context.ActionDescriptor.DisplayName;
            var time   = this.stopwatch.ElapsedMilliseconds;

            this.stopwatch.Stop();

            this.logger.LogInformation($"EXECUTED {method} {action} in {time}");
        }
 public void OnPageHandlerExecuted(PageHandlerExecutedContext ctx)
 {
     // Example requested in comments on answer.
     if (ctx.Result is PageResult pageResult)
     {
         pageResult.ViewData["Property"] = "Value";
     }
     // Another example requested in comments.
     // This can also be done in OnPageHandlerExecuting to short-circuit the response.
     ctx.Result = new RedirectResult("/url/to/redirect/to");
 }
        public void OnPageHandlerExecuted(PageHandlerExecutedContext context)
        {
            if (context.HandlerInstance is IBreadcrumbPage page)
            {
                var breadCrumbs = context.HttpContext.Items["FooBar"] as List <Breadcrumb> ?? new List <Breadcrumb>();

                breadCrumbs.AddRange(page.Breadcrumbs() ?? new Breadcrumb[0]);

                context.HttpContext.Items["FooBar"] = breadCrumbs;
            }
        }
示例#25
0
        public void OnPageHandlerExecuted(PageHandlerExecutedContext context)
        {
            Trace.WriteLine("Hello From Page Filter");
            var page  = context.HandlerInstance as PageModel;
            var claim = context.HttpContext.User.Claims.FirstOrDefault(c => c.Type == "Discriminator");

            if (claim != null)
            {
                page.ViewData["Discriminator"] = claim.Value;
            }
        }
示例#26
0
        private void HandleError(PageHandlerExecutedContext context)
        {
            context.Result = new ObjectResult(
                new AjaxResponse(
                    _errorInfoBuilder.BuildForException(context.Exception),
                    context.Exception is AbpAuthorizationException
                    )
                );

            EventBus.Trigger(this, new AbpHandledExceptionData(context.Exception));

            context.Exception = null; // Handled!
        }
 public void OnPageHandlerExecuted(PageHandlerExecutedContext context)
 {
     _timer.Stop();
     if (context.Exception == null)
     {
         _logger.LogRoutePerformance(context.ActionDescriptor.RelativePath,
                                     context.HttpContext.Request.Method,
                                     _timer.ElapsedMilliseconds);
     }
     //_logger.LogInformation("{PageName} {Method} model code took {ElapsedMilliseconds}.",
     //    context.ActionDescriptor.RelativePath,
     //    context.HttpContext.Request.Method,
     //    _timer.ElapsedMilliseconds);
 }
        public static void AfterOnPageHandlerExecuted(
            this DiagnosticListener diagnosticListener,
            PageHandlerExecutedContext handlerExecutedContext,
            IPageFilter filter)
        {
            Debug.Assert(diagnosticListener != null);
            Debug.Assert(handlerExecutedContext != null);
            Debug.Assert(filter != null);

            // Inlinable fast-path check if Diagnositcs is enabled
            if (diagnosticListener.IsEnabled())
            {
                AfterOnPageHandlerExecutedImpl(diagnosticListener, handlerExecutedContext, filter);
            }
        }
示例#29
0
        private Dictionary <string, object> GetModelObject(PageHandlerExecutedContext context)
        {
            if (context.ActionDescriptor.BoundProperties == null || context.ActionDescriptor.BoundProperties.Count == 0)
            {
                return(null);
            }
            var model = new Dictionary <string, object>();

            foreach (var prop in context.ActionDescriptor.BoundProperties)
            {
                if (prop is PageBoundPropertyDescriptor descriptor)
                {
                    model.Add(prop.Name, descriptor.Property.GetValue(context.HandlerInstance));
                }
            }
            return(model);
        }
        public void OnPageHandlerExecuted(PageHandlerExecutedContext context)
        {
            IServiceProvider   provider          = context.HttpContext.RequestServices;
            IUnitOfWorkManager unitOfWorkManager = provider.GetService <IUnitOfWorkManager>();

            //if (context.Exception != null && !context.ExceptionHandled)
            //{
            //    unitOfWorkManager?.Rollback();
            //}
            //else
            //{
            //    unitOfWorkManager?.Commit();
            //}
            if (context.Exception == null && context.ExceptionHandled)
            {
                unitOfWorkManager?.Commit();
            }
        }