Beispiel #1
0
        public void FormatFilter_ContextContainsFormat_Custom(
            string format,
            FormatSource place,
            string contentType)
        {
            // Arrange
            var mediaType = new StringSegment(contentType);

            var mockObjects              = new MockObjects(format, place);
            var resultExecutingContext   = mockObjects.CreateResultExecutingContext();
            var resourceExecutingContext = mockObjects.CreateResourceExecutingContext(new IFilterMetadata[] { });

            mockObjects.Options.FormatterMappings.SetMediaTypeMappingForFormat(
                format,
                MediaTypeHeaderValue.Parse(contentType));

            var filter = new FormatFilter(mockObjects.OptionsManager);

            // Act
            filter.OnResourceExecuting(resourceExecutingContext);
            filter.OnResultExecuting(resultExecutingContext);

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

            Assert.Single(objectResult.ContentTypes);
            MediaTypeAssert.Equal(mediaType, objectResult.ContentTypes[0]);
        }
    public async Task ExecuteAsync_ContentTypeProvidedFromResponseAndObjectResult_UsesResponseContentType()
    {
        // Arrange
        var executor = CreateExecutor();

        var httpContext   = new DefaultHttpContext();
        var actionContext = new ActionContext()
        {
            HttpContext = httpContext
        };

        httpContext.Request.Headers.Accept = "application/xml"; // This will not be used
        httpContext.Response.ContentType   = "text/plain";

        var result = new ObjectResult("input");

        result.Formatters.Add(new TestXmlOutputFormatter());
        result.Formatters.Add(new TestJsonOutputFormatter());
        result.Formatters.Add(new TestStringOutputFormatter()); // This will be chosen based on the content type

        // Act
        await executor.ExecuteAsync(actionContext, result);

        // Assert
        MediaTypeAssert.Equal("text/plain; charset=utf-8", httpContext.Response.ContentType);
    }
    public async Task ObjectResult_PerformsContentNegotiation_OnAllMediaRangeAcceptHeaderMediaType(
        string acceptHeader,
        string expectedContentType)
    {
        // Arrange
        var options = new MvcOptions();

        options.RespectBrowserAcceptHeader = true;

        var executor = CreateExecutor(options: options);

        var result = new ObjectResult("input");

        result.Formatters.Add(new TestJsonOutputFormatter());
        result.Formatters.Add(new TestXmlOutputFormatter());

        var actionContext = new ActionContext()
        {
            HttpContext = GetHttpContext(),
        };

        actionContext.HttpContext.Request.Headers.Accept = acceptHeader;

        // Act
        await executor.ExecuteAsync(actionContext, result);

        // Assert
        var responseContentType = actionContext.HttpContext.Response.Headers.ContentType;

        MediaTypeAssert.Equal(expectedContentType, responseContentType);
    }
Beispiel #4
0
        public void FormatFilter_ExplicitContentType_SetOnObjectResult_TakesPrecedence()
        {
            // Arrange
            var mediaType   = new StringSegment("application/foo");
            var mockObjects = new MockObjects("json", FormatSource.QueryData);
            var httpContext = new Mock <HttpContext>();

            httpContext.Setup(c => c.Response).Returns(new Mock <HttpResponse>().Object);
            httpContext.Setup(c => c.Request.Query["format"]).Returns("json");
            var actionContext = new ActionContext(httpContext.Object, new RouteData(), new ActionDescriptor());
            var objectResult  = new ObjectResult("Hello!");

            objectResult.ContentTypes.Add(new MediaTypeHeaderValue("application/foo"));
            var resultExecutingContext = new ResultExecutingContext(
                actionContext,
                new IFilterMetadata[] { },
                objectResult,
                controller: new object());

            var resourceExecutingContext = new ResourceExecutingContext(
                actionContext,
                new IFilterMetadata[] { });

            var filter = new FormatFilter(mockObjects.OptionsManager);

            // Act
            filter.OnResourceExecuting(resourceExecutingContext);
            filter.OnResultExecuting(resultExecutingContext);

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

            Assert.Equal(1, result.ContentTypes.Count);
            MediaTypeAssert.Equal(mediaType, result.ContentTypes[0]);
        }
    public async Task ExecuteAsync_ForProblemDetailsValue_UsesProblemDetailsContentType()
    {
        // Arrange
        var executor = CreateExecutor();

        var httpContext   = new DefaultHttpContext();
        var actionContext = new ActionContext()
        {
            HttpContext = httpContext
        };

        httpContext.Response.ContentType = "application/json"; // This will not be used

        var result = new ObjectResult(new ProblemDetails());

        result.Formatters.Add(new TestXmlOutputFormatter()); // This will be chosen based on the problem details content type
        result.Formatters.Add(new TestJsonOutputFormatter());
        result.Formatters.Add(new TestStringOutputFormatter());

        // Act
        await executor.ExecuteAsync(actionContext, result);

        // Assert
        MediaTypeAssert.Equal("application/problem+xml; charset=utf-8", httpContext.Response.ContentType);
    }
    public async Task ExecuteAsync_ForProblemDetailsValue_UsesProblemDetailsXMLContentType_BasedOnAcceptHeader()
    {
        // Arrange
        var executor = CreateExecutor();

        var httpContext   = new DefaultHttpContext();
        var actionContext = new ActionContext()
        {
            HttpContext = httpContext
        };

        httpContext.Request.Headers.Accept = "application/xml"; // This will not be used

        var result = new ObjectResult(new ProblemDetails())
        {
            ContentTypes = { "text/plain" }, // This will not be used
        };

        result.Formatters.Add(new TestJsonOutputFormatter());
        result.Formatters.Add(new TestXmlOutputFormatter()); // This will be chosen based on the Accept Headers "application/xml"
        result.Formatters.Add(new TestStringOutputFormatter());

        // Act
        await executor.ExecuteAsync(actionContext, result);

        // Assert
        MediaTypeAssert.Equal("application/problem+xml; charset=utf-8", httpContext.Response.ContentType);
    }
Beispiel #7
0
        public void FormatFilter_ContextContainsFormat_DefaultFormat(
            string format,
            FormatSource place,
            string contentType)
        {
            // Arrange
            var mediaType   = new StringSegment("application/json");
            var mockObjects = new MockObjects(format, place);

            var resultExecutingContext   = mockObjects.CreateResultExecutingContext();
            var resourceExecutingContext = mockObjects.CreateResourceExecutingContext(new IFilterMetadata[] { });

            var filter = new FormatFilter(mockObjects.OptionsManager);

            // Act
            filter.OnResourceExecuting(resourceExecutingContext);

            // Assert
            Assert.Null(resourceExecutingContext.Result);

            // Act
            filter.OnResultExecuting(resultExecutingContext);

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

            Assert.Single(objectResult.ContentTypes);
            MediaTypeAssert.Equal(mediaType, objectResult.ContentTypes[0]);
        }
Beispiel #8
0
        public void SelectFormatter_WithNoProvidedContentType_DoesConneg()
        {
            // Arrange
            var executor = CreateExecutor();

            var formatters = new List <IOutputFormatter>
            {
                new TestXmlOutputFormatter(),
                new TestJsonOutputFormatter(), // This will be chosen based on the accept header
            };

            var context = new OutputFormatterWriteContext(
                new DefaultHttpContext(),
                new TestHttpResponseStreamWriterFactory().CreateWriter,
                objectType: null,
                @object: null);

            context.HttpContext.Request.Headers[HeaderNames.Accept] = "application/json";

            // Act
            var formatter = executor.SelectFormatter(
                context,
                new MediaTypeCollection {
                "application/json"
            },
                formatters);

            // Assert
            Assert.Same(formatters[1], formatter);
            MediaTypeAssert.Equal("application/json", context.ContentType);
        }
Beispiel #9
0
    public void ProducesResponseTypeAttribute_SetsContentType()
    {
        // Arrange
        var mediaType1 = new StringSegment("application/json");
        var mediaType2 = new StringSegment("text/json;charset=utf-8");
        var producesContentAttribute = new ProducesResponseTypeAttribute(typeof(void), StatusCodes.Status200OK, "application/json", "text/json;charset=utf-8");

        // Assert
        Assert.Equal(2, producesContentAttribute.ContentTypes.Count);
        MediaTypeAssert.Equal(mediaType1, producesContentAttribute.ContentTypes[0]);
        MediaTypeAssert.Equal(mediaType2, producesContentAttribute.ContentTypes[1]);
    }
    public void FormatterMappings_SetFormatMapping_DiffSetGetFormat(string setFormat, string contentType, string getFormat)
    {
        // Arrange
        var options = new FormatterMappings();

        options.SetMediaTypeMappingForFormat(setFormat, MediaTypeHeaderValue.Parse(contentType));

        // Act
        var returnMediaType = options.GetMediaTypeMappingForFormat(getFormat);

        // Assert
        MediaTypeAssert.Equal(contentType, returnMediaType);
    }
Beispiel #11
0
    public void Constructor_SetsContentTypeAndParameters()
    {
        // Arrange
        var path              = Path.GetFullPath("helllo.txt");
        var contentType       = "text/plain; charset=us-ascii; p1=p1-value";
        var expectedMediaType = contentType;

        // Act
        var result = new VirtualFileResult(path, contentType);

        // Assert
        Assert.Equal(path, result.FileName);
        MediaTypeAssert.Equal(expectedMediaType, result.ContentType);
    }
Beispiel #12
0
        public void FormatFilter_ContextContainsFormat_InRouteAndQueryData()
        {
            // If the format is present in both route and query data, the one in route data wins

            // Arrange
            var mediaType   = new StringSegment("application/json");
            var mockObjects = new MockObjects("json", FormatSource.RouteData);
            var httpContext = new Mock <HttpContext>();

            httpContext.Setup(c => c.Response).Returns(new Mock <HttpResponse>().Object);

            // Query contains xml
            httpContext.Setup(c => c.Request.Query.ContainsKey("format")).Returns(true);
            httpContext.Setup(c => c.Request.Query["format"]).Returns("xml");

            // Routedata contains json
            var data = new RouteData();

            data.Values.Add("format", "json");

            var ac = new ActionContext(httpContext.Object, data, new ActionDescriptor());

            var resultExecutingContext = new ResultExecutingContext(
                ac,
                new IFilterMetadata[] { },
                new ObjectResult("Hello!"),
                controller: new object());

            var resourceExecutingContext = new ResourceExecutingContext(
                ac,
                new IFilterMetadata[] { },
                new List <IValueProviderFactory>());

            var filter = new FormatFilter(mockObjects.OptionsManager);

            // Act
            filter.OnResourceExecuting(resourceExecutingContext);
            filter.OnResultExecuting(resultExecutingContext);

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

            Assert.Single(objectResult.ContentTypes);
            MediaTypeAssert.Equal(mediaType, objectResult.ContentTypes[0]);
        }
Beispiel #13
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);
    }
        public void ProducesAttribute_SetsContentType()
        {
            // Arrange
            var mediaType1 = new StringSegment("application/json");
            var mediaType2 = new StringSegment("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
            producesContentAttribute.OnResultExecuting(resultExecutingContext);

            // Assert
            var objectResult = resultExecutingContext.Result as ObjectResult;

            Assert.Equal(2, objectResult.ContentTypes.Count);
            MediaTypeAssert.Equal(mediaType1, objectResult.ContentTypes[0]);
            MediaTypeAssert.Equal(mediaType2, objectResult.ContentTypes[1]);
        }
Beispiel #15
0
    public async Task ContentResult_ExecuteResultAsync_Response_NullContent_SetsContentTypeAndEncoding()
    {
        // Arrange
        var contentResult = new ContentResult
        {
            Content     = null,
            ContentType = new MediaTypeHeaderValue("text/plain")
            {
                Encoding = Encoding.Unicode
            }.ToString()
        };
        var httpContext   = GetHttpContext();
        var actionContext = GetActionContext(httpContext);

        // Act
        await contentResult.ExecuteResultAsync(actionContext);

        // Assert
        MediaTypeAssert.Equal("text/plain; charset=utf-16", httpContext.Response.ContentType);
    }
Beispiel #16
0
        public async Task ExecuteAsync_SetsContentTypeAndEncoding(
            MediaTypeHeaderValue contentType,
            string responseContentType,
            string expectedContentType)
        {
            // Arrange
            var view = CreateView(async(v) =>
            {
                await v.Writer.WriteAsync("abcd");
            });

            var context      = new DefaultHttpContext();
            var memoryStream = new MemoryStream();

            context.Response.Body        = memoryStream;
            context.Response.ContentType = responseContentType;

            var actionContext = new ActionContext(
                context,
                new RouteData(),
                new ActionDescriptor());
            var viewData = new ViewDataDictionary(new EmptyModelMetadataProvider());

            var viewExecutor = CreateViewExecutor();

            // Act
            await viewExecutor.ExecuteAsync(
                actionContext,
                view,
                viewData,
                Mock.Of <ITempDataDictionary>(),
                contentType?.ToString(),
                statusCode : null);

            // Assert
            MediaTypeAssert.Equal(expectedContentType, context.Response.ContentType);
            Assert.Equal("abcd", Encoding.UTF8.GetString(memoryStream.ToArray()));
        }
Beispiel #17
0
        public async Task ExecuteAsync_NoContentTypeProvidedForProblemDetails_UsesDefaultContentTypes()
        {
            // Arrange
            var executor = CreateExecutor();

            var httpContext   = new DefaultHttpContext();
            var actionContext = new ActionContext()
            {
                HttpContext = httpContext
            };

            var result = new ObjectResult(new ProblemDetails());

            result.Formatters.Add(new TestXmlOutputFormatter());  // This will be chosen based on the implicitly added content type
            result.Formatters.Add(new TestJsonOutputFormatter());
            result.Formatters.Add(new TestStringOutputFormatter());

            // Act
            await executor.ExecuteAsync(actionContext, result);

            // Assert
            MediaTypeAssert.Equal("application/problem+xml; charset=utf-8", httpContext.Response.ContentType);
        }