コード例 #1
0
    public async Task ViewComponentResult_NoContentTypeSet_PreservesResponseContentType(
        string responseContentType,
        string expectedContentType)
    {
        // Arrange
        var methodInfo = typeof(TextViewComponent).GetMethod(nameof(TextViewComponent.Invoke));
        var descriptor = new ViewComponentDescriptor()
        {
            FullName   = "Full.Name.Text",
            ShortName  = "Text",
            TypeInfo   = typeof(TextViewComponent).GetTypeInfo(),
            MethodInfo = methodInfo,
            Parameters = methodInfo.GetParameters(),
        };

        var actionContext = CreateActionContext(descriptor);

        actionContext.HttpContext.Response.ContentType = expectedContentType;

        var viewComponentResult = new ViewComponentResult()
        {
            Arguments         = new { name = "World!" },
            ViewComponentName = "Text",
            TempData          = _tempDataDictionary,
        };

        // Act
        await viewComponentResult.ExecuteResultAsync(actionContext);

        // Assert
        Assert.Equal(expectedContentType, actionContext.HttpContext.Response.ContentType);
    }
コード例 #2
0
        public async Task ExecuteAsync_ViewComponentResult_AllowsNullViewDataAndTempData()
        {
            // Arrange
            var descriptor = new ViewComponentDescriptor()
            {
                FullName = "Full.Name.Text",
                ShortName = "Text",
                TypeInfo = typeof(TextViewComponent).GetTypeInfo(),
                MethodInfo = typeof(TextViewComponent).GetMethod(nameof(TextViewComponent.Invoke)),
            };

            var actionContext = CreateActionContext(descriptor);

            var viewComponentResult = new ViewComponentResult
            {
                Arguments = new { name = "World!" },
                ViewData = null,
                TempData = null,
                ViewComponentName = "Text"
            };

            // Act
            await viewComponentResult.ExecuteResultAsync(actionContext);
            // No assert, just confirm it didn't throw
        }
コード例 #3
0
    public async Task ExecuteAsync_ViewComponentResult_AllowsNullViewDataAndTempData()
    {
        // Arrange
        var methodInfo = typeof(TextViewComponent).GetMethod(nameof(TextViewComponent.Invoke));
        var descriptor = new ViewComponentDescriptor()
        {
            FullName   = "Full.Name.Text",
            ShortName  = "Text",
            TypeInfo   = typeof(TextViewComponent).GetTypeInfo(),
            MethodInfo = methodInfo,
            Parameters = methodInfo.GetParameters(),
        };

        var actionContext = CreateActionContext(descriptor);

        var viewComponentResult = new ViewComponentResult
        {
            Arguments         = new { name = "World!" },
            ViewData          = null,
            TempData          = null,
            ViewComponentName = "Text"
        };

        // Act
        await viewComponentResult.ExecuteResultAsync(actionContext);

        // No assert, just confirm it didn't throw
    }
コード例 #4
0
    public async Task ExecuteResultAsync_ExecutesViewComponent_ByFullName()
    {
        // Arrange
        var methodInfo = typeof(TextViewComponent).GetMethod(nameof(TextViewComponent.Invoke));
        var descriptor = new ViewComponentDescriptor()
        {
            FullName   = "Full.Name.Text",
            ShortName  = "Text",
            TypeInfo   = typeof(TextViewComponent).GetTypeInfo(),
            MethodInfo = methodInfo,
            Parameters = methodInfo.GetParameters(),
        };

        var actionContext = CreateActionContext(descriptor);

        var viewComponentResult = new ViewComponentResult()
        {
            Arguments         = new { name = "World!" },
            ViewComponentName = "Full.Name.Text",
            TempData          = _tempDataDictionary,
        };

        // Act
        await viewComponentResult.ExecuteResultAsync(actionContext);

        // Assert
        var body = ReadBody(actionContext.HttpContext.Response);

        Assert.Equal("Hello, World!", body);
    }
コード例 #5
0
    public async Task ExecuteResultAsync_SetsStatusCode()
    {
        // Arrange
        var methodInfo = typeof(TextViewComponent).GetMethod(nameof(TextViewComponent.Invoke));
        var descriptor = new ViewComponentDescriptor()
        {
            FullName   = "Full.Name.Text",
            ShortName  = "Text",
            TypeInfo   = typeof(TextViewComponent).GetTypeInfo(),
            MethodInfo = methodInfo,
            Parameters = methodInfo.GetParameters(),
        };

        var actionContext = CreateActionContext(descriptor);

        var viewComponentResult = new ViewComponentResult()
        {
            Arguments         = new { name = "World!" },
            ViewComponentType = typeof(TextViewComponent),
            StatusCode        = 404,
            TempData          = _tempDataDictionary,
        };

        // Act
        await viewComponentResult.ExecuteResultAsync(actionContext);

        // Assert
        Assert.Equal(404, actionContext.HttpContext.Response.StatusCode);
    }
コード例 #6
0
    public async Task ExecuteResultAsync_Throws_IfViewComponentCouldNotBeFound_ByType()
    {
        // Arrange
        var expected = $"A view component named '{typeof(TextViewComponent).FullName}' could not be found. " +
                       "A view component must be a public non-abstract class, not contain any generic parameters, and either be decorated " +
                       "with 'ViewComponentAttribute' or have a class name ending with the 'ViewComponent' suffix. " +
                       "A view component must not be decorated with 'NonViewComponentAttribute'.";

        var actionContext = CreateActionContext();
        var services      = CreateServices(diagnosticListener: null, context: actionContext.HttpContext);

        services.AddSingleton <IViewComponentSelector>();


        var viewComponentResult = new ViewComponentResult
        {
            ViewComponentType = typeof(TextViewComponent),
            TempData          = _tempDataDictionary,
        };

        // Act and Assert
        var exception = await Assert.ThrowsAsync <InvalidOperationException>(
            () => viewComponentResult.ExecuteResultAsync(actionContext));

        Assert.Equal(expected, exception.Message);
    }
コード例 #7
0
        /// <summary>
        /// Render component to string
        /// </summary>
        /// <param name="componentName">Component name</param>
        /// <param name="arguments">Arguments</param>
        /// <returns>Result</returns>
        protected virtual string RenderViewComponentToString(string componentName, object arguments = null)
        {
            //original implementation: https://github.com/aspnet/Mvc/blob/dev/src/Microsoft.AspNetCore.Mvc.ViewFeatures/Internal/ViewComponentResultExecutor.cs
            //we customized it to allow running from controllers

            //TODO add support for parameters (pass ViewComponent as input parameter)
            if (string.IsNullOrEmpty(componentName))
            {
                throw new ArgumentNullException(nameof(componentName));
            }

            IActionContextAccessor actionContextAccessor = HttpContext.RequestServices.GetService(typeof(IActionContextAccessor)) as IActionContextAccessor;

            if (actionContextAccessor == null)
            {
                throw new Exception("IActionContextAccessor cannot be resolved");
            }

            ActionContext context = actionContextAccessor.ActionContext;

            ViewComponentResult viewComponentResult = ViewComponent(componentName, arguments);

            ViewDataDictionary viewData = this.ViewData;

            if (viewData == null)
            {
                throw new NotImplementedException();
                //TODO viewData = new ViewDataDictionary(_modelMetadataProvider, context.ModelState);
            }

            ITempDataDictionary tempData = this.TempData;

            if (tempData == null)
            {
                throw new NotImplementedException();
                //TODO tempData = _tempDataDictionaryFactory.GetTempData(context.HttpContext);
            }

            using (StringWriter writer = new StringWriter())
            {
                ViewContext viewContext = new ViewContext(
                    context,
                    NullView.Instance,
                    viewData,
                    tempData,
                    writer,
                    new HtmlHelperOptions());

                // IViewComponentHelper is stateful, we want to make sure to retrieve it every time we need it.
                IViewComponentHelper viewComponentHelper = context.HttpContext.RequestServices.GetRequiredService <IViewComponentHelper>();
                (viewComponentHelper as IViewContextAware)?.Contextualize(viewContext);

                System.Threading.Tasks.Task <Microsoft.AspNetCore.Html.IHtmlContent> result = viewComponentResult.ViewComponentType == null?
                                                                                              viewComponentHelper.InvokeAsync(viewComponentResult.ViewComponentName, viewComponentResult.Arguments) :
                                                                                                  viewComponentHelper.InvokeAsync(viewComponentResult.ViewComponentType, viewComponentResult.Arguments);

                result.Result.WriteTo(writer, HtmlEncoder.Default);
                return(writer.ToString());
            }
        }
コード例 #8
0
        public async Task <ViewComponentResult> OnGetWeaponAmmoAsync(string item)
        {
            var result = new ViewComponentResult()
            {
                ViewComponentName = "WeaponAmmo", Arguments = item
            };

            return(await Task.FromResult(result));
        }
コード例 #9
0
        public async Task <ViewComponentResult> OnGetAddMechAsync(string mechs)
        {
            var result = new ViewComponentResult()
            {
                ViewComponentName = "AddMech", Arguments = mechs
            };

            return(await Task.FromResult(result));
        }
コード例 #10
0
        public async Task <ViewComponentResult> OnGetWeaponItemsAsync(string category)
        {
            var result = new ViewComponentResult()
            {
                ViewComponentName = "WeaponItems", Arguments = category
            };

            return(await Task.FromResult(result));
        }
コード例 #11
0
        public IActionResult CustomViewComponentResultWithViewData()
        {
            var viewComponent = new ViewComponentResult
            {
                ViewData = new ViewDataDictionary(new EmptyModelMetadataProvider(), new ModelStateDictionary())
            };

            viewComponent.ViewData.Model = TestObjectFactory.GetListOfResponseModels();
            return(viewComponent);
        }
コード例 #12
0
 public static object GetModel(this IActionResult actionResult)
 {
     return(actionResult switch
     {
         ViewResult result => result.Model,
         PartialViewResult result => result.Model,
         PageResult result => result.Model,
         JsonResult result => result.Value,
         ViewComponentResult result => result.Model,
         _ => null
     });
コード例 #13
0
        public async Task ExecuteAsync(ActionContext context, ViewComponentResult viewComponentResult)
        {
            var response = context.HttpContext.Response;

            var viewData = viewComponentResult.ViewData;

            if (viewData == null)
            {
                viewData = new ViewDataDictionary(_modelMetadataProvider, context.ModelState);
            }

            var tempData = viewComponentResult.TempData;

            if (tempData == null)
            {
                tempData = _tempDataDictionaryFactory.GetTempData(context.HttpContext);
            }

            string   resolvedContentType;
            Encoding resolvedContentTypeEncoding;

            ResponseContentTypeHelper.ResolveContentTypeAndEncoding(
                viewComponentResult.ContentType,
                response.ContentType,
                ViewExecutor.DefaultContentType,
                out resolvedContentType,
                out resolvedContentTypeEncoding);

            response.ContentType = resolvedContentType;

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

            using (var writer = new HttpResponseStreamWriter(response.Body, resolvedContentTypeEncoding))
            {
                var viewContext = new ViewContext(
                    context,
                    NullView.Instance,
                    viewData,
                    tempData,
                    writer,
                    _htmlHelperOptions);

                // IViewComponentHelper is stateful, we want to make sure to retrieve it every time we need it.
                var viewComponentHelper = context.HttpContext.RequestServices.GetRequiredService <IViewComponentHelper>();
                (viewComponentHelper as IViewContextAware)?.Contextualize(viewContext);

                var result = await GetViewComponentResult(viewComponentHelper, _logger, viewComponentResult);

                result.WriteTo(writer, _htmlEncoder);
            }
        }
コード例 #14
0
    public void Model_ExposesViewDataModel()
    {
        // Arrange
        var customModel = new object();
        var viewResult  = new ViewComponentResult
        {
            ViewData = new ViewDataDictionary(new EmptyModelMetadataProvider())
            {
                Model = customModel
            },
        };

        // Act & Assert
        Assert.Same(customModel, viewResult.Model);
    }
コード例 #15
0
        public async Task ExecuteAsync(ActionContext context, ViewComponentResult viewComponentResult)
        {
            var response = context.HttpContext.Response;

            var viewData = viewComponentResult.ViewData;
            if (viewData == null)
            {
                viewData = new ViewDataDictionary(_modelMetadataProvider, context.ModelState);
            }

            var tempData = viewComponentResult.TempData;
            if (tempData == null)
            {
                tempData = _tempDataDictionaryFactory.GetTempData(context.HttpContext);
            }

            string resolvedContentType;
            Encoding resolvedContentTypeEncoding;
            ResponseContentTypeHelper.ResolveContentTypeAndEncoding(
                viewComponentResult.ContentType,
                response.ContentType,
                ViewExecutor.DefaultContentType,
                out resolvedContentType,
                out resolvedContentTypeEncoding);

            response.ContentType = resolvedContentType;

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

            using (var writer = new HttpResponseStreamWriter(response.Body, resolvedContentTypeEncoding))
            {
                var viewContext = new ViewContext(
                    context,
                    NullView.Instance,
                    viewData,
                    tempData,
                    writer,
                    _htmlHelperOptions);

                (_viewComponentHelper as IViewContextAware)?.Contextualize(viewContext);
                var result = await GetViewComponentResult(_viewComponentHelper, _logger, viewComponentResult);

                result.WriteTo(writer, _htmlEncoder);
            }
        }
コード例 #16
0
        public async Task ExecuteResultAsync_Throws_IfNameOrTypeIsNotSet()
        {
            // Arrange
            var expected =
                "Either the 'ViewComponentName' or 'ViewComponentType' " +
                "property must be set in order to invoke a view component.";

            var actionContext = CreateActionContext();

            var viewComponentResult = new ViewComponentResult
            {
                TempData = _tempDataDictionary,
            };

            // Act and Assert
            var exception = await Assert.ThrowsAsync<InvalidOperationException>(
                () => viewComponentResult.ExecuteResultAsync(actionContext));
            Assert.Equal(expected, exception.Message);
        }
コード例 #17
0
    public async Task ViewComponentResult_SetsContentTypeHeader(
        string contentType,
        string expectedContentType)
    {
        // Arrange
        var methodInfo = typeof(TextViewComponent).GetMethod(nameof(TextViewComponent.Invoke));
        var descriptor = new ViewComponentDescriptor()
        {
            FullName   = "Full.Name.Text",
            ShortName  = "Text",
            TypeInfo   = typeof(TextViewComponent).GetTypeInfo(),
            MethodInfo = methodInfo,
            Parameters = methodInfo.GetParameters(),
        };

        var actionContext = CreateActionContext(descriptor);

        var contentTypeBeforeViewResultExecution = contentType?.ToString();

        var viewComponentResult = new ViewComponentResult()
        {
            Arguments         = new { name = "World!" },
            ViewComponentName = "Text",
            ContentType       = contentType,
            TempData          = _tempDataDictionary,
        };

        // Act
        await viewComponentResult.ExecuteResultAsync(actionContext);

        // Assert
        var resultContentType = actionContext.HttpContext.Response.ContentType;

        MediaTypeAssert.Equal(expectedContentType, resultContentType);

        // Check if the original instance provided by the user has not changed.
        // Since we do not have access to the new instance created within the view executor,
        // check if at least the content is the same.
        var contentTypeAfterViewResultExecution = contentType?.ToString();

        MediaTypeAssert.Equal(contentTypeBeforeViewResultExecution, contentTypeAfterViewResultExecution);
    }
コード例 #18
0
    public async Task ExecuteResultAsync_WithCustomViewComponentHelper_ForLargeText()
    {
        // Arrange
        var expected   = new string('a', 64 * 1024 * 1024);
        var methodInfo = typeof(TextViewComponent).GetMethod(nameof(TextViewComponent.Invoke));
        var descriptor = new ViewComponentDescriptor()
        {
            FullName   = "Full.Name.Text",
            ShortName  = "Text",
            TypeInfo   = typeof(TextViewComponent).GetTypeInfo(),
            MethodInfo = methodInfo,
            Parameters = methodInfo.GetParameters(),
        };
        var result = Task.FromResult <IHtmlContent>(new HtmlContentBuilder().AppendHtml(expected));

        var helper = Mock.Of <IViewComponentHelper>(h => h.InvokeAsync(It.IsAny <Type>(), It.IsAny <object>()) == result);

        var httpContext = new DefaultHttpContext();
        var services    = CreateServices(diagnosticListener: null, httpContext, new[] { descriptor });

        services.AddSingleton <IViewComponentHelper>(helper);

        httpContext.RequestServices = services.BuildServiceProvider();
        httpContext.Response.Body   = new MemoryStream();

        var actionContext = new ActionContext(httpContext, new RouteData(), new ActionDescriptor());

        var viewComponentResult = new ViewComponentResult()
        {
            Arguments         = new { name = "World!" },
            ViewComponentType = typeof(TextViewComponent),
            TempData          = _tempDataDictionary,
        };

        // Act
        await viewComponentResult.ExecuteResultAsync(actionContext);

        // Assert
        var body = ReadBody(actionContext.HttpContext.Response);

        Assert.Equal(expected, body);
    }
コード例 #19
0
    public async Task ExecuteResultAsync_Throws_IfNameOrTypeIsNotSet()
    {
        // Arrange
        var expected =
            "Either the 'ViewComponentName' or 'ViewComponentType' " +
            "property must be set in order to invoke a view component.";

        var actionContext = CreateActionContext();

        var viewComponentResult = new ViewComponentResult
        {
            TempData = _tempDataDictionary,
        };

        // Act and Assert
        var exception = await Assert.ThrowsAsync <InvalidOperationException>(
            () => viewComponentResult.ExecuteResultAsync(actionContext));

        Assert.Equal(expected, exception.Message);
    }
コード例 #20
0
    public async Task ExecuteResultAsync_Throws_IfServicesNotRegistered()
    {
        // Arrange
        var actionContext = new ActionContext(new DefaultHttpContext()
        {
            RequestServices = Mock.Of <IServiceProvider>(),
        }, new RouteData(), new ActionDescriptor());
        var expected =
            "Unable to find the required services. Please add all the required services by calling " +
            $"'IServiceCollection.AddControllersWithViews()' inside the call to 'ConfigureServices(...)' " +
            "in the application startup code.";

        var viewResult = new ViewComponentResult();

        // Act
        var ex = await Assert.ThrowsAsync <InvalidOperationException>(() => viewResult.ExecuteResultAsync(actionContext));

        // Assert
        Assert.Equal(expected, ex.Message);
    }
コード例 #21
0
    public async Task ExecuteResultAsync_Throws_IfViewComponentCouldNotBeFound_ByName()
    {
        // Arrange
        var expected = "A view component named 'Text' could not be found. A view component must be " +
                       "a public non-abstract class, not contain any generic parameters, and either be decorated " +
                       "with 'ViewComponentAttribute' or have a class name ending with the 'ViewComponent' suffix. " +
                       "A view component must not be decorated with 'NonViewComponentAttribute'.";

        var actionContext = CreateActionContext();

        var viewComponentResult = new ViewComponentResult
        {
            ViewComponentName = "Text",
            TempData          = _tempDataDictionary,
        };

        // Act and Assert
        var exception = await Assert.ThrowsAsync <InvalidOperationException>(
            () => viewComponentResult.ExecuteResultAsync(actionContext));

        Assert.Equal(expected, exception.Message);
    }
コード例 #22
0
    public async Task ViewComponentResult_SetsContentTypeHeader_OverrideResponseContentType()
    {
        // Arrange
        var methodInfo = typeof(TextViewComponent).GetMethod(nameof(TextViewComponent.Invoke));
        var descriptor = new ViewComponentDescriptor()
        {
            FullName   = "Full.Name.Text",
            ShortName  = "Text",
            TypeInfo   = typeof(TextViewComponent).GetTypeInfo(),
            MethodInfo = methodInfo,
            Parameters = methodInfo.GetParameters(),
        };

        var actionContext = CreateActionContext(descriptor);

        var expectedContentType = "text/html; charset=utf-8";

        actionContext.HttpContext.Response.ContentType = "application/x-will-be-overridden";

        var viewComponentResult = new ViewComponentResult()
        {
            Arguments         = new { name = "World!" },
            ViewComponentName = "Text",
            ContentType       = new MediaTypeHeaderValue("text/html")
            {
                Encoding = Encoding.UTF8
            }.ToString(),
            TempData = _tempDataDictionary,
        };

        // Act
        await viewComponentResult.ExecuteResultAsync(actionContext);

        // Assert
        Assert.Equal(expectedContentType, actionContext.HttpContext.Response.ContentType);
    }
コード例 #23
0
        public async Task ExecuteResultAsync_Throws_IfViewComponentCouldNotBeFound_ByType()
        {
            // Arrange
            var expected = $"A view component named '{typeof(TextViewComponent).FullName}' could not be found.";

            var actionContext = CreateActionContext();
            var services = CreateServices(diagnosticListener: null, context: actionContext.HttpContext);
            services.AddSingleton<IViewComponentSelector>();


            var viewComponentResult = new ViewComponentResult
            {
                ViewComponentType = typeof(TextViewComponent),
                TempData = _tempDataDictionary,
            };

            // Act and Assert
            var exception = await Assert.ThrowsAsync<InvalidOperationException>(
                () => viewComponentResult.ExecuteResultAsync(actionContext));
            Assert.Equal(expected, exception.Message);
        }
コード例 #24
0
 private Task<IHtmlContent> GetViewComponentResult(IViewComponentHelper viewComponentHelper, ILogger logger, ViewComponentResult result)
 {
     if (result.ViewComponentType == null && result.ViewComponentName == null)
     {
         throw new InvalidOperationException(Resources.FormatViewComponentResult_NameOrTypeMustBeSet(
             nameof(ViewComponentResult.ViewComponentName),
             nameof(ViewComponentResult.ViewComponentType)));
     }
     else if (result.ViewComponentType == null)
     {
         logger.ViewComponentResultExecuting(result.ViewComponentName);
         return viewComponentHelper.InvokeAsync(result.ViewComponentName, result.Arguments);
     }
     else
     {
         logger.ViewComponentResultExecuting(result.ViewComponentType);
         return viewComponentHelper.InvokeAsync(result.ViewComponentType, result.Arguments);
     }
 }
コード例 #25
0
        public IActionResult Feed(Guid?gameId, Guid?userId, Guid?oldestId, DateTime?oldestDate, bool?articlesOnly)
        {
            ViewComponentResult component = ViewComponent("Feed", new { count = 10, gameId, userId, oldestId, oldestDate, articlesOnly });

            return(component);
        }
コード例 #26
0
        public Task <IActionResult> Feed(Guid?gameId, Guid?userId, Guid?oldestId, DateTime?oldestDate, bool?articlesOnly)
        {
            ViewComponentResult component = ViewComponent("Feed", new { count = 10, gameId, userId, oldestId, oldestDate, articlesOnly });

            return(Task.FromResult((IActionResult)component));
        }
コード例 #27
0
 private Task <IHtmlContent> GetViewComponentResult(IViewComponentHelper viewComponentHelper, ILogger logger, ViewComponentResult result)
 {
     if (result.ViewComponentType == null && result.ViewComponentName == null)
     {
         throw new InvalidOperationException(Resources.FormatViewComponentResult_NameOrTypeMustBeSet(
                                                 nameof(ViewComponentResult.ViewComponentName),
                                                 nameof(ViewComponentResult.ViewComponentType)));
     }
     else if (result.ViewComponentType == null)
     {
         logger.ViewComponentResultExecuting(result.ViewComponentName);
         return(viewComponentHelper.InvokeAsync(result.ViewComponentName, result.Arguments));
     }
     else
     {
         logger.ViewComponentResultExecuting(result.ViewComponentType);
         return(viewComponentHelper.InvokeAsync(result.ViewComponentType, result.Arguments));
     }
 }
コード例 #28
0
        public async Task ExecuteResultAsync_ExecutesViewComponent_ByType()
        {
            // Arrange
            var descriptor = new ViewComponentDescriptor()
            {
                FullName = "Full.Name.Text",
                ShortName = "Text",
                TypeInfo = typeof(TextViewComponent).GetTypeInfo(),
                MethodInfo = typeof(TextViewComponent).GetMethod(nameof(TextViewComponent.Invoke)),
            };

            var actionContext = CreateActionContext(descriptor);

            var viewComponentResult = new ViewComponentResult()
            {
                Arguments = new { name = "World!" },
                ViewComponentType = typeof(TextViewComponent),
                TempData = _tempDataDictionary,
            };

            // Act
            await viewComponentResult.ExecuteResultAsync(actionContext);

            // Assert
            var body = ReadBody(actionContext.HttpContext.Response);
            Assert.Equal("Hello, World!", body);
        }
コード例 #29
0
        public async Task ExecuteResultAsync_ExecutesViewComponent_AndWritesDiagnosticSource()
        {
            // Arrange
            var descriptor = new ViewComponentDescriptor()
            {
                FullName = "Full.Name.Text",
                ShortName = "Text",
                TypeInfo = typeof(TextViewComponent).GetTypeInfo(),
                MethodInfo = typeof(TextViewComponent).GetMethod(nameof(TextViewComponent.Invoke)),
            };

            var adapter = new TestDiagnosticListener();

            var actionContext = CreateActionContext(adapter, descriptor);

            var viewComponentResult = new ViewComponentResult()
            {
                Arguments = new { name = "World!" },
                ViewComponentName = "Text",
                TempData = _tempDataDictionary,
            };

            // Act
            await viewComponentResult.ExecuteResultAsync(actionContext);

            // Assert
            var body = ReadBody(actionContext.HttpContext.Response);
            Assert.Equal("Hello, World!", body);

            Assert.NotNull(adapter.BeforeViewComponent?.ActionDescriptor);
            Assert.NotNull(adapter.BeforeViewComponent?.ViewComponentContext);
            Assert.NotNull(adapter.BeforeViewComponent?.ViewComponent);
            Assert.NotNull(adapter.AfterViewComponent?.ActionDescriptor);
            Assert.NotNull(adapter.AfterViewComponent?.ViewComponentContext);
            Assert.NotNull(adapter.AfterViewComponent?.ViewComponentResult);
            Assert.NotNull(adapter.AfterViewComponent?.ViewComponent);
        }
コード例 #30
0
        public async Task ExecuteResultAsync_Throws_IfViewComponentCouldNotBeFound_ByName()
        {
            // Arrange
            var expected = "A view component named 'Text' could not be found.";

            var actionContext = CreateActionContext();

            var viewComponentResult = new ViewComponentResult
            {
                ViewComponentName = "Text",
                TempData = _tempDataDictionary,
            };

            // Act and Assert
            var exception = await Assert.ThrowsAsync<InvalidOperationException>(
                () => viewComponentResult.ExecuteResultAsync(actionContext));
            Assert.Equal(expected, exception.Message);
        }
コード例 #31
0
        public async Task ExecuteResultAsync_SetsStatusCode()
        {
            // Arrange
            var descriptor = new ViewComponentDescriptor()
            {
                FullName = "Full.Name.Text",
                ShortName = "Text",
                TypeInfo = typeof(TextViewComponent).GetTypeInfo(),
                MethodInfo = typeof(TextViewComponent).GetMethod(nameof(TextViewComponent.Invoke))
            };

            var actionContext = CreateActionContext(descriptor);

            var viewComponentResult = new ViewComponentResult()
            {
                Arguments = new { name = "World!" },
                ViewComponentType = typeof(TextViewComponent),
                StatusCode = 404,
                TempData = _tempDataDictionary,
            };

            // Act
            await viewComponentResult.ExecuteResultAsync(actionContext);

            // Assert
            Assert.Equal(404, actionContext.HttpContext.Response.StatusCode);
        }
コード例 #32
0
        public async Task ViewComponentResult_NoContentTypeSet_PreservesResponseContentType(
            string responseContentType,
            string expectedContentType)
        {
            // Arrange
            var descriptor = new ViewComponentDescriptor()
            {
                FullName = "Full.Name.Text",
                ShortName = "Text",
                TypeInfo = typeof(TextViewComponent).GetTypeInfo(),
                MethodInfo = typeof(TextViewComponent).GetMethod(nameof(TextViewComponent.Invoke)),
            };

            var actionContext = CreateActionContext(descriptor);

            actionContext.HttpContext.Response.ContentType = expectedContentType;

            var viewComponentResult = new ViewComponentResult()
            {
                Arguments = new { name = "World!" },
                ViewComponentName = "Text",
                TempData = _tempDataDictionary,
            };

            // Act
            await viewComponentResult.ExecuteResultAsync(actionContext);

            // Assert
            Assert.Equal(expectedContentType, actionContext.HttpContext.Response.ContentType);
        }
コード例 #33
0
        public async Task ViewComponentResult_SetsContentTypeHeader_OverrideResponseContentType()
        {
            // Arrange
            var descriptor = new ViewComponentDescriptor()
            {
                FullName = "Full.Name.Text",
                ShortName = "Text",
                TypeInfo = typeof(TextViewComponent).GetTypeInfo(),
                MethodInfo = typeof(TextViewComponent).GetMethod(nameof(TextViewComponent.Invoke)),
            };

            var actionContext = CreateActionContext(descriptor);

            var expectedContentType = "text/html; charset=utf-8";
            actionContext.HttpContext.Response.ContentType = "application/x-will-be-overridden";

            var viewComponentResult = new ViewComponentResult()
            {
                Arguments = new { name = "World!" },
                ViewComponentName = "Text",
                ContentType = new MediaTypeHeaderValue("text/html") { Encoding = Encoding.UTF8 }.ToString(),
                TempData = _tempDataDictionary,
            };

            // Act
            await viewComponentResult.ExecuteResultAsync(actionContext);

            // Assert
            Assert.Equal(expectedContentType, actionContext.HttpContext.Response.ContentType);
        }
コード例 #34
0
        public async Task ViewComponentResult_SetsContentTypeHeader(
            string contentType,
            string expectedContentType)
        {
            // Arrange
            var descriptor = new ViewComponentDescriptor()
            {
                FullName = "Full.Name.Text",
                ShortName = "Text",
                TypeInfo = typeof(TextViewComponent).GetTypeInfo(),
                MethodInfo = typeof(TextViewComponent).GetMethod(nameof(TextViewComponent.Invoke)),
            };

            var actionContext = CreateActionContext(descriptor);

            var contentTypeBeforeViewResultExecution = contentType?.ToString();

            var viewComponentResult = new ViewComponentResult()
            {
                Arguments = new { name = "World!" },
                ViewComponentName = "Text",
                ContentType = contentType,
                TempData = _tempDataDictionary,
            };

            // Act
            await viewComponentResult.ExecuteResultAsync(actionContext);

            // Assert
            var resultContentType = actionContext.HttpContext.Response.ContentType;
            MediaTypeAssert.Equal(expectedContentType, resultContentType);

            // Check if the original instance provided by the user has not changed.
            // Since we do not have access to the new instance created within the view executor,
            // check if at least the content is the same.
            var contentTypeAfterViewResultExecution = contentType?.ToString();
            MediaTypeAssert.Equal(contentTypeBeforeViewResultExecution, contentTypeAfterViewResultExecution);
        }