public ControllerActionInvoker(
            [NotNull] ActionContext actionContext,
            [NotNull] IReadOnlyList<IFilterProvider> filterProviders,
            [NotNull] IControllerFactory controllerFactory,
            [NotNull] ControllerActionDescriptor descriptor,
            [NotNull] IInputFormattersProvider inputFormatterProvider,
            [NotNull] IControllerActionArgumentBinder controllerActionArgumentBinder,
            [NotNull] IModelBinderProvider modelBinderProvider,
            [NotNull] IModelValidatorProviderProvider modelValidatorProviderProvider,
            [NotNull] IValueProviderFactoryProvider valueProviderFactoryProvider,
            [NotNull] IScopedInstance<ActionBindingContext> actionBindingContextAccessor,
            [NotNull] ITempDataDictionary tempData)
            : base(
                  actionContext, 
                  filterProviders,
                  inputFormatterProvider, 
                  modelBinderProvider, 
                  modelValidatorProviderProvider, 
                  valueProviderFactoryProvider,
                  actionBindingContextAccessor)
        {
            _descriptor = descriptor;
            _controllerFactory = controllerFactory;
            _argumentBinder = controllerActionArgumentBinder;
            _tempData = tempData;

            if (descriptor.MethodInfo == null)
            {
                throw new ArgumentException(
                    Resources.FormatPropertyOfTypeCannotBeNull("MethodInfo",
                                                               typeof(ControllerActionDescriptor)),
                    "descriptor");
            }
        }
Пример #2
0
 protected BasePageHelper(ViewContext viewContext)
 {
     //_rootViewContext = viewContext;
     //while (_rootViewContext.IsChildAction)
     //{
     //    _rootViewContext = _rootViewContext.ParentActionViewContext;
     //}
     //_rootTempData = _rootViewContext.TempData;
     _rootViewContext = viewContext;
     _rootTempData = _rootViewContext.TempData;
 }
Пример #3
0
        /// <summary>
        /// Initializes a new instance of <see cref="ViewContext"/>.
        /// </summary>
        /// <param name="actionContext">The <see cref="ActionContext"/>.</param>
        /// <param name="view">The <see cref="IView"/> being rendered.</param>
        /// <param name="viewData">The <see cref="ViewDataDictionary"/>.</param>
        /// <param name="tempData">The <see cref="ITempDataDictionary"/>.</param>
        /// <param name="writer">The <see cref="TextWriter"/> to render output to.</param>
        public ViewContext(
            ActionContext actionContext,
            IView view,
            ViewDataDictionary viewData,
            ITempDataDictionary tempData,
            TextWriter writer,
            HtmlHelperOptions htmlHelperOptions)
            : base(actionContext)
        {
            if (actionContext == null)
            {
                throw new ArgumentNullException(nameof(actionContext));
            }

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

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

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

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

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

            View = view;
            ViewData = viewData;
            TempData = tempData;
            Writer = writer;

            _formContext = _defaultFormContext;
            ClientValidationEnabled = htmlHelperOptions.ClientValidationEnabled;
            Html5DateRenderingMode = htmlHelperOptions.Html5DateRenderingMode;
            ValidationSummaryMessageElement = htmlHelperOptions.ValidationSummaryMessageElement;
            ValidationMessageElement = htmlHelperOptions.ValidationMessageElement;
        }
 public ControllerActionInvokerProvider(
     IControllerFactory controllerFactory,
     IInputFormattersProvider inputFormattersProvider,
     IEnumerable<IFilterProvider> filterProviders,
     IControllerActionArgumentBinder argumentBinder,
     IModelBinderProvider modelBinderProvider,
     IModelValidatorProviderProvider modelValidationProviderProvider,
     IValueProviderFactoryProvider valueProviderFactoryProvider,
     IScopedInstance<ActionBindingContext> actionBindingContextAccessor,
     ITempDataDictionary tempData)
 {
     _controllerFactory = controllerFactory;
     _inputFormattersProvider = inputFormattersProvider;
     _filterProviders = filterProviders.OrderBy(item => item.Order).ToArray();
     _argumentBinder = argumentBinder;
     _modelBinderProvider = modelBinderProvider;
     _modelValidationProviderProvider = modelValidationProviderProvider;
     _valueProviderFactoryProvider = valueProviderFactoryProvider;
     _actionBindingContextAccessor = actionBindingContextAccessor;
     _tempData = tempData;
 }
 public ControllerActionInvokerProvider(
     IControllerFactory controllerFactory,
     IEnumerable<IFilterProvider> filterProviders,
     IControllerActionArgumentBinder argumentBinder,
     IOptions<MvcOptions> optionsAccessor,
     IScopedInstance<ActionBindingContext> actionBindingContextAccessor,
     ITempDataDictionary tempData,
     ILoggerFactory loggerFactory)
 {
     _controllerFactory = controllerFactory;
     _filterProviders = filterProviders.OrderBy(item => item.Order).ToArray();
     _argumentBinder = argumentBinder;
     _inputFormatters = optionsAccessor.Options.InputFormatters.ToArray();
     _outputFormatters = optionsAccessor.Options.OutputFormatters.ToArray();
     _modelBinders = optionsAccessor.Options.ModelBinders.ToArray();
     _modelValidatorProviders = optionsAccessor.Options.ModelValidatorProviders.ToArray();
     _valueProviderFactories = optionsAccessor.Options.ValueProviderFactories.ToArray();
     _actionBindingContextAccessor = actionBindingContextAccessor;
     _tempData = tempData;
     _maxModelValidationErrors = optionsAccessor.Options.MaxModelValidationErrors;
     _loggerFactory = loggerFactory;
 }
 public TestControllerActionInvoker(
     ActionContext actionContext,
     IFilterProvider[] filterProvider,
     MockControllerFactory controllerFactory,
     ControllerActionDescriptor descriptor,
     IInputFormattersProvider inputFormattersProvider,
     IControllerActionArgumentBinder controllerActionArgumentBinder,
     IModelBinderProvider modelBinderProvider,
     IModelValidatorProviderProvider modelValidatorProviderProvider,
     IValueProviderFactoryProvider valueProviderFactoryProvider,
     IScopedInstance<ActionBindingContext> actionBindingContext,
     ITempDataDictionary tempData)
     : base(
           actionContext,
           filterProvider,
           controllerFactory,
           descriptor,
           inputFormattersProvider,
           controllerActionArgumentBinder,
           modelBinderProvider,
           modelValidatorProviderProvider,
           valueProviderFactoryProvider,
           actionBindingContext,
           tempData)
 {
     ControllerFactory = controllerFactory;
 }
Пример #7
0
        /// <summary>
        /// Asynchronously renders the specified <paramref name="view"/> to the response body.
        /// </summary>
        /// <param name="view">The <see cref="IView"/> to render.</param>
        /// <param name="actionContext">The <see cref="ActionContext"/> for the current executing action.</param>
        /// <param name="viewData">The <see cref="ViewDataDictionary"/> for the view being rendered.</param>
        /// <param name="tempData">The <see cref="ITempDataDictionary"/> for the view being rendered.</param>
        /// <returns>A <see cref="Task"/> that represents the asynchronous rendering.</returns>
        public static async Task ExecuteAsync(
            IView view,
            ActionContext actionContext,
            ViewDataDictionary viewData,
            ITempDataDictionary tempData,
            HtmlHelperOptions htmlHelperOptions,
            MediaTypeHeaderValue contentType)
        {
            if (view == null)
            {
                throw new ArgumentNullException(nameof(view));
            }

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

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

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

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

            var response = actionContext.HttpContext.Response;

            if (contentType != null && contentType.Encoding == null)
            {
                // Do not modify the user supplied content type, so copy it instead
                contentType = contentType.Copy();
                contentType.Encoding = Encoding.UTF8;
            }

            // Priority list for setting content-type:
            //      1. passed in contentType (likely set by the user on the result)
            //      2. response.ContentType (likely set by the user in controller code)
            //      3. ViewExecutor.DefaultContentType (sensible default)
            response.ContentType = contentType?.ToString() ?? response.ContentType ?? DefaultContentType.ToString();

            using (var writer = new HttpResponseStreamWriter(response.Body, contentType?.Encoding ?? DefaultContentType.Encoding))
            {
                var viewContext = new ViewContext(
                    actionContext,
                    view,
                    viewData,
                    tempData,
                    writer,
                    htmlHelperOptions);

                await view.RenderAsync(viewContext);
                // Invoke FlushAsync to ensure any buffered content is asynchronously written to the underlying
                // response. In the absence of this line, the buffer gets synchronously written to the response
                // as part of the Dispose which has a perf impact.
                await writer.FlushAsync();
            }
        }
Пример #8
0
 public static void Set <T>(this ITempDataDictionary tempData, string key, T value) where T : class
 {
     tempData[key] = JsonConvert.SerializeObject(value);
 }
 private TestControllerActionInvoker CreateInvoker(
     IFilter filter,
     bool actionThrows = false,
     ITempDataDictionary tempData = null)
 {
     return CreateInvoker(new[] { filter }, actionThrows, tempData);
 }
Пример #10
0
 public static bool HasStatusMessage(this ITempDataDictionary tempData)
 {
     return((tempData.Peek(WellKnownTempData.SuccessMessage) ??
             tempData.Peek(WellKnownTempData.ErrorMessage) ??
             tempData.Peek("StatusMessageModel")) != null);
 }
Пример #11
0
 public TempDataMessageQueue(ITempDataDictionaryFactory tempFactory, IHttpContextAccessor accessor)
 {
     _tempData = tempFactory.GetTempData(accessor.HttpContext);
 }
Пример #12
0
 public TempDataPropertyTracker LoadAndTrackChanges(object subject, ITempDataDictionary tempData)
 {
     return(new TempDataPropertyTracker(subject, tempData, LoadPropertyState(subject, tempData), SavePropertyValue));
 }
Пример #13
0
 public static void AddAlerts(this ITempDataDictionary tempData, List <Alert> alerts)
 {
     tempData[Alert.TempDataKey] = JsonConvert.SerializeObject(alerts);
 }
 public static T Get <T>(this ITempDataDictionary tempData, string key) where T : class
 {
     tempData.TryGetValue(key, out object o);
     return(o is null ? null : JsonSerializer.Parse <T>((string)o));
 }
Пример #15
0
 public static void AddErrorMessage(this ITempDataDictionary tempData, string message)
 {
     tempData["ErrorMessage"] = message;
 }
Пример #16
0
 /// <summary>
 /// Retrieves the queued messages for the current response without clearing them.
 /// </summary>
 /// <param name="this"></param>
 /// <returns></returns>
 public static List <FlashMessageModel> Queued(ITempDataDictionary dictionary)
 {
     // For this transport Peek() and Queued() have equal implementations.
     return(Peek(dictionary));
 }
Пример #17
0
        // ModelStateを追加
        public static void AddModelState(this ITempDataDictionary tempData, ModelStateDictionary modelState)
        {
            var json = JsonConvertHelper.SerializeModelState(modelState);

            tempData.Add(_modelStateKey, json);
        }
Пример #18
0
        private TaskController CreateController(ITaskRepository repo, Guid currUserId, ITempDataDictionary tempData = null)
        {
            var usrMgr        = TestHelper.GetUserManager();
            var httpContext   = Substitute.For <HttpContext>();
            var currPrincipal = new ClaimsPrincipal();

            httpContext.User.Returns(currPrincipal);
            usrMgr.GetUserId(currPrincipal).Returns(currUserId.ToString());
            if (tempData == null)
            {
                tempData = Substitute.For <ITempDataDictionary>();
            }
            var controller = new TaskController(repo, usrMgr)
            {
                TempData = tempData
            };

            controller.ControllerContext.HttpContext = httpContext;
            return(controller);
        }
 public static void AddSuccessMessage(this ITempDataDictionary tempData, string message)
 {
     tempData[ControllerConstants.SuccessMessage] = message;
 }
Пример #20
0
 public FlashesTagHelper(ITempDataDictionaryFactory factory, IHttpContextAccessor contextAccessor)
 {
     tempData = factory.GetTempData(contextAccessor.HttpContext);
 }
 public TestControllerActionInvoker(
     ActionContext actionContext,
     IFilterProvider[] filterProvider,
     MockControllerFactory controllerFactory,
     ControllerActionDescriptor descriptor,
     IReadOnlyList<IInputFormatter> inputFormatters,
     IReadOnlyList<IOutputFormatter> outputFormatters,
     IControllerActionArgumentBinder controllerActionArgumentBinder,
     IReadOnlyList<IModelBinder> modelBinders,
     IReadOnlyList<IModelValidatorProvider> modelValidatorProviders,
     IReadOnlyList<IValueProviderFactory> valueProviderFactories,
     IScopedInstance<ActionBindingContext> actionBindingContext,
     ITempDataDictionary tempData,
     ILoggerFactory loggerFactory,
     int maxAllowedErrorsInModelState)
     : base(
           actionContext,
           filterProvider,
           controllerFactory,
           descriptor,
           inputFormatters,
           outputFormatters,
           controllerActionArgumentBinder,
           modelBinders,
           modelValidatorProviders,
           valueProviderFactories,
           actionBindingContext,
           tempData,
           loggerFactory,
           maxAllowedErrorsInModelState)
 {
     ControllerFactory = controllerFactory;
 }
Пример #22
0
 public ViewUseCasePresenter(ISession s, ITempDataDictionary t, ModelStateDictionary m) : base(s, t, m)
 {
 }
Пример #23
0
        /// <summary>
        /// Retrieves information from the <see cref="TempDataDictionary"/> using a specified key.
        /// </summary>
        /// <typeparam name="T">The type of data to retrieve.</typeparam>
        /// <param name="tempData">Represents a set of data that persists only from one request to the next.</param>
        /// <param name="key">The key to use in the <see cref="TempDataDictionary"/>.</param>
        /// <returns>The data persisted in the <see cref="TempDataDictionary"/> under the specified key.</returns>
        public static T Get <T>(this ITempDataDictionary tempData, string key)
        {
            tempData.TryGetValue(key, out var @object);

            return(@object == null ? default : JsonConvert.DeserializeObject <T>((string)@object));
        }
Пример #24
0
 public static void SetMessages(this ITempDataDictionary tempDataDictionary, string storageKey, IEnumerable <Message> messages)
 {
     tempDataDictionary[storageKey] = JsonSerializer.Serialize(messages);
 }
Пример #25
0
 private void ClearNotification(ITempDataDictionary tempData)
 {
     tempData.Remove(NotificationHelpers.NotificationKey);
 }
Пример #26
0
        private SaveTempDataFilter GetFilter(ITempDataDictionary tempDataDictionary)
        {
            var tempDataFactory = GetTempDataDictionaryFactory(tempDataDictionary);

            return(new SaveTempDataFilter(tempDataFactory.Object));
        }
Пример #27
0
 public static T Get <T>(this ITempDataDictionary tempData, string key) where T : class
 {
     tempData.TryGetValue(key, out object o);
     return(o == null ? null : JsonConvert.DeserializeObject <T>((string)o));
 }
 public static void AddSuccessMessage(this ITempDataDictionary tempData, string message)
 {
     tempData[WebConstants.TempDataSuccessMessage] = message;
 }
Пример #29
0
 public static void AddErrorMessage(this ITempDataDictionary tempData, string errorMessage)
 {
     tempData[TempDataErrorMessageKey] = errorMessage;
 }
Пример #30
0
 public static string GetStringValue(this ITempDataDictionary tempData, string key)
 {
     return(tempData.GetValue <string>(key, default));
 }
        private TestControllerActionInvoker CreateInvoker(
            IFilter[] filters,
            bool actionThrows = false,
            ITempDataDictionary tempData = null)
        {
            var actionDescriptor = new ControllerActionDescriptor()
            {
                FilterDescriptors = new List<FilterDescriptor>(),
                Parameters = new List<ParameterDescriptor>(),
            };

            if (actionThrows)
            {
                actionDescriptor.MethodInfo = typeof(ControllerActionInvokerTest).GetMethod("ThrowingActionMethod");
            }
            else
            {
                actionDescriptor.MethodInfo = typeof(ControllerActionInvokerTest).GetMethod("ActionMethod");
            }

            tempData = tempData ?? new Mock<ITempDataDictionary>().Object;
            var httpContext = new Mock<HttpContext>(MockBehavior.Loose);
            var httpRequest = new DefaultHttpContext().Request;
            var httpResponse = new DefaultHttpContext().Response;
            var mockFormattersProvider = new Mock<IOutputFormattersProvider>();
            mockFormattersProvider.SetupGet(o => o.OutputFormatters)
                                  .Returns(
                                        new List<IOutputFormatter>()
                                        {
                                            new JsonOutputFormatter()
                                        });
            httpContext.SetupGet(c => c.Request).Returns(httpRequest);
            httpContext.SetupGet(c => c.Response).Returns(httpResponse);
            httpContext.Setup(o => o.RequestServices.GetService(typeof(IOutputFormattersProvider)))
                       .Returns(mockFormattersProvider.Object);
            httpContext.Setup(o => o.RequestServices.GetService(typeof(ITempDataDictionary)))
                       .Returns(tempData);
            httpResponse.Body = new MemoryStream();

            var options = new Mock<IOptions<MvcOptions>>();
            options.SetupGet(o => o.Options)
                       .Returns(new MvcOptions());
            httpContext.Setup(o => o.RequestServices.GetService(typeof(IOptions<MvcOptions>)))
                       .Returns(options.Object);

            var actionContext = new ActionContext(
                httpContext: httpContext.Object,
                routeData: new RouteData(),
                actionDescriptor: actionDescriptor);

            var filterProvider = new Mock<IFilterProvider>(MockBehavior.Strict);
            filterProvider
                .Setup(fp => fp.OnProvidersExecuting(It.IsAny<FilterProviderContext>()))
                .Callback<FilterProviderContext>(context =>
                    {
                        foreach (var filter in filters.Select(f => new FilterItem(null, f)))
                        {
                            context.Results.Add(filter);
                        }
                    });

            filterProvider.Setup(fp => fp.OnProvidersExecuted(It.IsAny<FilterProviderContext>()))
                          .Verifiable();

            filterProvider.SetupGet(fp => fp.Order)
                          .Returns(DefaultOrder.DefaultFrameworkSortOrder);


            var inputFormattersProvider = new Mock<IInputFormattersProvider>();
            inputFormattersProvider.SetupGet(o => o.InputFormatters)
                                            .Returns(new List<IInputFormatter>());
            var excludeFilterProvider = new Mock<IValidationExcludeFiltersProvider>();
            excludeFilterProvider.SetupGet(o => o.ExcludeFilters)
                                 .Returns(new List<IExcludeTypeValidationFilter>());
            var invoker = new TestControllerActionInvoker(
                actionContext,
                new[] { filterProvider.Object },
                new MockControllerFactory(this),
                actionDescriptor,
                inputFormattersProvider.Object,
                Mock.Of<IControllerActionArgumentBinder>(),
                new MockModelBinderProvider(),
                new MockModelValidatorProviderProvider(),
                new MockValueProviderFactoryProvider(),
                new MockScopedInstance<ActionBindingContext>(),
                tempData);

            return invoker;
        }
 public RedirectToActionResult RedirectAfterEnrollment(ITempDataDictionary tempData, Controller controller)
 {
     return(controller.RedirectToAction("Requests"));
 }
Пример #33
0
        /// <summary>
        /// Executes a view asynchronously.
        /// </summary>
        /// <param name="actionContext">The <see cref="ActionContext"/> associated with the current request.</param>
        /// <param name="view">The <see cref="IView"/>.</param>
        /// <param name="viewData">The <see cref="ViewDataDictionary"/>.</param>
        /// <param name="tempData">The <see cref="ITempDataDictionary"/>.</param>
        /// <param name="contentType">
        /// The content-type header value to set in the response. If <c>null</c>, <see cref="DefaultContentType"/> will be used.
        /// </param>
        /// <param name="statusCode">
        /// The HTTP status code to set in the response. May be <c>null</c>.
        /// </param>
        /// <returns>A <see cref="Task"/> which will complete when view execution is completed.</returns>
        public virtual async Task ExecuteAsync(
            ActionContext actionContext,
            IView view,
            ViewDataDictionary viewData,
            ITempDataDictionary tempData,
            MediaTypeHeaderValue contentType,
            int? statusCode)
        {
            if (actionContext == null)
            {
                throw new ArgumentNullException(nameof(actionContext));
            }

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

            var services = actionContext.HttpContext.RequestServices;
            if (viewData == null)
            {
                var metadataProvider = services.GetRequiredService<IModelMetadataProvider>();
                viewData = new ViewDataDictionary(metadataProvider);
            }

            if (tempData == null)
            {
                tempData = services.GetRequiredService<ITempDataDictionary>();
            }

            var response = actionContext.HttpContext.Response;

            if (contentType != null && contentType.Encoding == null)
            {
                // Do not modify the user supplied content type, so copy it instead
                contentType = contentType.Copy();
                contentType.Encoding = Encoding.UTF8;
            }

            // Priority list for setting content-type:
            //      1. passed in contentType (likely set by the user on the result)
            //      2. response.ContentType (likely set by the user in controller code)
            //      3. ViewExecutor.DefaultContentType (sensible default)
            response.ContentType = contentType?.ToString() ?? response.ContentType ?? DefaultContentType.ToString();

            if (statusCode != null)
            {
                response.StatusCode = statusCode.Value;
            }

            var encoding = contentType?.Encoding ?? DefaultContentType.Encoding;
            using (var writer = WriterFactory.CreateWriter(response.Body, encoding))
            {
                var viewContext = new ViewContext(
                    actionContext,
                    view,
                    viewData,
                    tempData,
                    writer,
                    ViewOptions.HtmlHelperOptions);
                
                DiagnosticSource.BeforeView(view, viewContext);

                await view.RenderAsync(viewContext);

                DiagnosticSource.AfterView(view, viewContext);

                // Perf: Invoke FlushAsync to ensure any buffered content is asynchronously written to the underlying
                // response asynchronously. In the absence of this line, the buffer gets synchronously written to the
                // response as part of the Dispose which has a perf impact.
                await writer.FlushAsync();
            }
        }
 private TestControllerActionInvoker CreateInvoker(
     IFilter filter,
     bool actionThrows = false,
     ITempDataDictionary tempData = null,
     int maxAllowedErrorsInModelState = 200)
 {
     return CreateInvoker(new[] { filter }, actionThrows, tempData, maxAllowedErrorsInModelState);
 }
Пример #35
0
 public Validate(ITempDataDictionary temp) => tempData = temp;
Пример #36
0
 public static bool GetBooleanValue(this ITempDataDictionary tempData, string key)
 {
     return(tempData.GetValue <bool>(key, default));
 }
Пример #37
0
 public static void Put <T>(this ITempDataDictionary td, string key, T data) where T : class, new()
 {
     td[key] = JsonConvert.SerializeObject(data);
 }
 public static void AddErrorMessage(this ITempDataDictionary tempData, string message)
 {
     tempData[WebConstants.TempDataErrorMessageKey] = message;
 }
Пример #39
0
 /// <summary>
 /// Creates a new instance of <see cref="SaveTempDataFilter"/>.
 /// </summary>
 /// <param name="tempData">The <see cref="ITempDataDictionary"/> for the current request.</param>
 public SaveTempDataFilter(ITempDataDictionary tempData)
 {
     _tempData = tempData;
 }
Пример #40
0
 public static void AddSuccessMessage(
     this ITempDataDictionary tempData,
     string message)
 {
     tempData[TempDataSuccessMessageKey] = message;
 }
        private TestControllerActionInvoker CreateInvoker(
            IFilter[] filters,
            bool actionThrows = false,
            ITempDataDictionary tempData = null,
            int maxAllowedErrorsInModelState = 200)
        {
            var actionDescriptor = new ControllerActionDescriptor()
            {
                FilterDescriptors = new List<FilterDescriptor>(),
                Parameters = new List<ParameterDescriptor>(),
            };

            if (actionThrows)
            {
                actionDescriptor.MethodInfo = typeof(ControllerActionInvokerTest).GetMethod("ThrowingActionMethod");
            }
            else
            {
                actionDescriptor.MethodInfo = typeof(ControllerActionInvokerTest).GetMethod("ActionMethod");
            }

            tempData = tempData ?? new Mock<ITempDataDictionary>().Object;
            var httpContext = new Mock<HttpContext>(MockBehavior.Loose);
            var httpRequest = new DefaultHttpContext().Request;
            var httpResponse = new DefaultHttpContext().Response;

            httpContext.SetupGet(c => c.Request).Returns(httpRequest);
            httpContext.SetupGet(c => c.Response).Returns(httpResponse);
            httpContext.Setup(o => o.RequestServices.GetService(typeof(ITempDataDictionary)))
                       .Returns(tempData);
            httpContext.Setup(o => o.RequestServices.GetService(typeof(ILogger<ObjectResult>)))
                       .Returns(new Mock<ILogger<ObjectResult>>().Object);

            httpResponse.Body = new MemoryStream();

            var formatter = new Mock<IOutputFormatter>();
            formatter
                .Setup(f => f.CanWriteResult(It.IsAny<OutputFormatterContext>(), It.IsAny<MediaTypeHeaderValue>()))
                .Returns(true);

            formatter
                .Setup(f => f.WriteAsync(It.IsAny<OutputFormatterContext>()))
                .Returns<OutputFormatterContext>(async c =>
                {
                    await c.HttpContext.Response.WriteAsync(c.Object.ToString());
                });

            var options = new MvcOptions();
            options.OutputFormatters.Add(formatter.Object);

            var optionsAccessor = new Mock<IOptions<MvcOptions>>();
            optionsAccessor
                .SetupGet(o => o.Options)
                .Returns(options);

            httpContext
                .Setup(o => o.RequestServices.GetService(typeof(IOptions<MvcOptions>)))
                .Returns(optionsAccessor.Object);

            var actionContext = new ActionContext(
                httpContext: httpContext.Object,
                routeData: new RouteData(),
                actionDescriptor: actionDescriptor);

            var filterProvider = new Mock<IFilterProvider>(MockBehavior.Strict);
            filterProvider
                .Setup(fp => fp.OnProvidersExecuting(It.IsAny<FilterProviderContext>()))
                .Callback<FilterProviderContext>(context =>
                    {
                        foreach (var filter in filters.Select(f => new FilterItem(null, f)))
                        {
                            context.Results.Add(filter);
                        }
                    });

            filterProvider.Setup(fp => fp.OnProvidersExecuted(It.IsAny<FilterProviderContext>()))
                          .Verifiable();

            filterProvider.SetupGet(fp => fp.Order)
                          .Returns(DefaultOrder.DefaultFrameworkSortOrder);

            var invoker = new TestControllerActionInvoker(
                actionContext,
                new[] { filterProvider.Object },
                new MockControllerFactory(this),
                actionDescriptor,
                new IInputFormatter[0],
                new IOutputFormatter[0],
                Mock.Of<IControllerActionArgumentBinder>(),
                new IModelBinder[0],
                new IModelValidatorProvider[0],
                new IValueProviderFactory[0],
                new MockScopedInstance<ActionBindingContext>(),
                tempData,
                new NullLoggerFactory(),
                maxAllowedErrorsInModelState);

            return invoker;
        }
        public static T Peek <T>(this ITempDataDictionary tempData, string key) where T : class
        {
            object o = tempData.Peek(key);

            return(o == null ? null : JsonSerializer.Deserialize <T>((string)o));
        }
Пример #43
0
        /// <summary>
        /// Executes a view asynchronously.
        /// </summary>
        /// <param name="actionContext">The <see cref="ActionContext"/> associated with the current request.</param>
        /// <param name="view">The <see cref="IView"/>.</param>
        /// <param name="viewData">The <see cref="ViewDataDictionary"/>.</param>
        /// <param name="tempData">The <see cref="ITempDataDictionary"/>.</param>
        /// <param name="contentType">
        /// The content-type header value to set in the response. If <c>null</c>,
        /// <see cref="DefaultContentType"/> will be used.
        /// </param>
        /// <param name="statusCode">
        /// The HTTP status code to set in the response. May be <c>null</c>.
        /// </param>
        /// <returns>A <see cref="Task"/> which will complete when view execution is completed.</returns>
        public virtual async Task ExecuteAsync(
            ActionContext actionContext,
            IView view,
            ViewDataDictionary viewData,
            ITempDataDictionary tempData,
            string contentType,
            int? statusCode)
        {
            if (actionContext == null)
            {
                throw new ArgumentNullException(nameof(actionContext));
            }

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

            if (viewData == null)
            {
                var services = actionContext.HttpContext.RequestServices;
                var metadataProvider = services.GetRequiredService<IModelMetadataProvider>();
                viewData = new ViewDataDictionary(metadataProvider, actionContext.ModelState);
            }

            if (tempData == null)
            {
                tempData = TempDataFactory.GetTempData(actionContext.HttpContext);
            }

            var response = actionContext.HttpContext.Response;

            string resolvedContentType = null;
            Encoding resolvedContentTypeEncoding = null;
            ResponseContentTypeHelper.ResolveContentTypeAndEncoding(
                contentType,
                response.ContentType,
                DefaultContentType,
                out resolvedContentType,
                out resolvedContentTypeEncoding);

            response.ContentType = resolvedContentType;

            if (statusCode != null)
            {
                response.StatusCode = statusCode.Value;
            }

            using (var writer = WriterFactory.CreateWriter(response.Body, resolvedContentTypeEncoding))
            {
                var viewContext = new ViewContext(
                    actionContext,
                    view,
                    viewData,
                    tempData,
                    writer,
                    ViewOptions.HtmlHelperOptions);

                DiagnosticSource.BeforeView(view, viewContext);

                await view.RenderAsync(viewContext);

                DiagnosticSource.AfterView(view, viewContext);

                // Perf: Invoke FlushAsync to ensure any buffered content is asynchronously written to the underlying
                // response asynchronously. In the absence of this line, the buffer gets synchronously written to the
                // response as part of the Dispose which has a perf impact.
                await writer.FlushAsync();
            }
        }
 public static void Put <T>(this ITempDataDictionary tempData, string key, T value) where T : class
 {
     tempData[key] = JsonSerializer.Serialize(value);
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="TempDataBuilder"/> class.
 /// </summary>
 /// <param name="tempData"><see cref="ITempDataDictionary"/> to built.</param>
 public TempDataBuilder(ITempDataDictionary tempData)
 {
     CommonValidator.CheckForNullReference(tempData, nameof(ITempDataDictionary));
     this.TempData = tempData;
 }
Пример #46
0
 /// <summary>
 /// Adds information to the <see cref="TempDataDictionary"/> using a specified key.
 /// </summary>
 /// <typeparam name="T">The type of data to persist.</typeparam>
 /// <param name="tempData">Represents a set of data that persists only from one request to the next.</param>
 /// <param name="key">The key to use in the <see cref="TempDataDictionary"/>.</param>
 /// <param name="value">The value to persist.</param>
 public static void Put <T>(this ITempDataDictionary tempData, string key, T value) => tempData[key] = JsonConvert.SerializeObject(value);