Esempio n. 1
0
 public ContentNegotiationResult Negotiate(Type type, HttpRequestMessage request, 
     IEnumerable<MediaTypeFormatter> formatters)
 {
     var result = new ContentNegotiationResult(_jsonFormatter,
         new MediaTypeHeaderValue("application/json"));
     return result;
 }
Esempio n. 2
0
        public ContentNegotiationResult Negotiate(Type type, HttpRequestMessage request, IEnumerable<MediaTypeFormatter> formatters)
        {
            var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
            json.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
            json.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;

            #if DEBUG
            json.SerializerSettings.Formatting = Formatting.Indented;
            #else
            json.SerializerSettings.Formatting = Formatting.None;
            #endif

            var result = new ContentNegotiationResult(json, new MediaTypeHeaderValue("application/json"));
            return result;
        }
        protected static HttpResponseMessage BuildDiagnosisResponse(HttpResponseMessage response, 
                                               ContentNegotiationResult result, string appCode, string errMessage, string errStackTrace)
        {
            var origStatusCode = response.StatusCode;
            SDataDiagnosis errorContent = new SDataDiagnosis()
            {
                severity = "Error",
                applicationCode = appCode,
                message = errMessage,
                stackTrace = errStackTrace
            };

            HttpResponseMessage errorResponse = new HttpResponseMessage()
            {
                StatusCode = origStatusCode,
                Content = new ObjectContent<SDataDiagnosis>(
                    errorContent,
                    result.Formatter,
                    result.MediaType.MediaType)
            };
            response.Headers.ToList().ForEach(i => errorResponse.Headers.Add(i.Key, i.Value));
            return errorResponse;
        }
        public void ExecuteAsync_ForApiController_ReturnsCorrectResponse_WhenContentNegotationSucceeds()
        {
            // Arrange
            Uri expectedLocation = CreateLocation();
            object expectedContent = CreateContent();
            ApiController controller = CreateController();
            MediaTypeFormatter expectedInputFormatter = CreateFormatter();
            MediaTypeFormatter expectedOutputFormatter = CreateFormatter();
            MediaTypeHeaderValue expectedMediaType = CreateMediaType();
            ContentNegotiationResult negotiationResult = new ContentNegotiationResult(expectedOutputFormatter,
                expectedMediaType);

            Expression<Func<IEnumerable<MediaTypeFormatter>, bool>> formattersMatch = (f) =>
                f != null && f.AsArray().Length == 1 && f.AsArray()[0] == expectedInputFormatter;

            using (HttpRequestMessage expectedRequest = CreateRequest())
            {
                Mock<IContentNegotiator> spy = new Mock<IContentNegotiator>();
                spy.Setup(n => n.Negotiate(typeof(object), expectedRequest, It.Is(formattersMatch))).Returns(
                    negotiationResult);
                IContentNegotiator contentNegotiator = spy.Object;

                using (HttpConfiguration configuration = CreateConfiguration(expectedInputFormatter,
                    contentNegotiator))
                {
                    controller.Configuration = configuration;
                    controller.Request = expectedRequest;

                    IHttpActionResult result = CreateProductUnderTest(expectedLocation, expectedContent, controller);

                    // Act
                    Task<HttpResponseMessage> task = result.ExecuteAsync(CancellationToken.None);

                    // Assert
                    Assert.NotNull(task);
                    task.WaitUntilCompleted();

                    using (HttpResponseMessage response = task.Result)
                    {
                        Assert.NotNull(response);
                        Assert.Equal(HttpStatusCode.Created, response.StatusCode);
                        Assert.Same(expectedLocation, response.Headers.Location);
                        HttpContent content = response.Content;
                        Assert.IsType<ObjectContent<object>>(content);
                        ObjectContent<object> typedContent = (ObjectContent<object>)content;
                        Assert.Same(expectedContent, typedContent.Value);
                        Assert.Same(expectedOutputFormatter, typedContent.Formatter);
                        Assert.NotNull(typedContent.Headers);
                        Assert.Equal(expectedMediaType, typedContent.Headers.ContentType);
                        Assert.Same(expectedRequest, response.RequestMessage);
                    }
                }
            }
        }
        public void ExecuteAsync_Returns_CorrectResponse_WhenContentNegotiationSucceeds()
        {
            // Arrange
            Uri expectedLocation = CreateLocation();
            object expectedContent = CreateContent();
            MediaTypeFormatter expectedFormatter = CreateFormatter();
            MediaTypeHeaderValue expectedMediaType = CreateMediaType();
            ContentNegotiationResult negotiationResult = new ContentNegotiationResult(expectedFormatter,
                expectedMediaType);

            using (HttpRequestMessage expectedRequest = CreateRequest())
            {
                IEnumerable<MediaTypeFormatter> expectedFormatters = CreateFormatters();

                Mock<IContentNegotiator> spy = new Mock<IContentNegotiator>();
                spy.Setup(n => n.Negotiate(typeof(object), expectedRequest, expectedFormatters)).Returns(
                    negotiationResult);
                IContentNegotiator contentNegotiator = spy.Object;

                IHttpActionResult result = CreateProductUnderTest(expectedLocation, expectedContent, contentNegotiator,
                    expectedRequest, expectedFormatters);

                // Act
                Task<HttpResponseMessage> task = result.ExecuteAsync(CancellationToken.None);

                // Assert
                Assert.NotNull(task);
                task.WaitUntilCompleted();

                using (HttpResponseMessage response = task.Result)
                {
                    Assert.NotNull(response);
                    Assert.Equal(HttpStatusCode.Created, response.StatusCode);
                    Assert.Same(expectedLocation, response.Headers.Location);
                    HttpContent content = response.Content;
                    Assert.IsType<ObjectContent<object>>(content);
                    ObjectContent<object> typedContent = (ObjectContent<object>)content;
                    Assert.Same(expectedContent, typedContent.Value);
                    Assert.Same(expectedFormatter, typedContent.Formatter);
                    Assert.NotNull(typedContent.Headers);
                    Assert.Equal(expectedMediaType, typedContent.Headers.ContentType);
                    Assert.Same(expectedRequest, response.RequestMessage);
                }
            }
        }
        public void ExecuteAsync_ForApiController_ReturnsCorrectResponse_WhenContentNegotationSucceeds()
        {
            // Arrange
            ModelStateDictionary modelState = CreateModelState();
            string expectedModelStateKey = "ModelStateKey";
            string expectedModelStateExceptionMessage = "ModelStateExceptionMessage";
            modelState.AddModelError(expectedModelStateKey, new InvalidOperationException(
                expectedModelStateExceptionMessage));
            ApiController controller = CreateController();
            MediaTypeFormatter expectedInputFormatter = CreateFormatter();
            MediaTypeFormatter expectedOutputFormatter = CreateFormatter();
            MediaTypeHeaderValue expectedMediaType = CreateMediaType();
            ContentNegotiationResult negotiationResult = new ContentNegotiationResult(expectedOutputFormatter,
                expectedMediaType);

            Expression<Func<IEnumerable<MediaTypeFormatter>, bool>> formattersMatch = (f) =>
                f != null && f.AsArray().Length == 1 && f.AsArray()[0] == expectedInputFormatter;

            using (HttpRequestMessage expectedRequest = CreateRequest())
            {
                Mock<IContentNegotiator> spy = new Mock<IContentNegotiator>();
                spy.Setup(n => n.Negotiate(typeof(HttpError), expectedRequest, It.Is(formattersMatch))).Returns(
                    negotiationResult);
                IContentNegotiator contentNegotiator = spy.Object;

                using (HttpConfiguration configuration = CreateConfiguration(expectedInputFormatter,
                    contentNegotiator))
                {
                    configuration.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;
                    controller.Configuration = configuration;
                    controller.Request = expectedRequest;

                    IHttpActionResult result = CreateProductUnderTest(modelState, controller);

                    // Act
                    Task<HttpResponseMessage> task = result.ExecuteAsync(CancellationToken.None);

                    // Assert
                    Assert.NotNull(task);
                    task.WaitUntilCompleted();

                    using (HttpResponseMessage response = task.Result)
                    {
                        Assert.NotNull(response);
                        Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
                        HttpContent content = response.Content;
                        Assert.IsType<ObjectContent<HttpError>>(content);
                        ObjectContent<HttpError> typedContent = (ObjectContent<HttpError>)content;
                        HttpError error = (HttpError)typedContent.Value;
                        Assert.NotNull(error);
                        HttpError modelStateError = error.ModelState;
                        Assert.NotNull(modelStateError);
                        Assert.True(modelState.ContainsKey(expectedModelStateKey));
                        object modelStateValue = modelStateError[expectedModelStateKey];
                        Assert.IsType(typeof(string[]), modelStateValue);
                        string[] typedModelStateValue = (string[])modelStateValue;
                        Assert.Equal(1, typedModelStateValue.Length);
                        Assert.Same(expectedModelStateExceptionMessage, typedModelStateValue[0]);
                        Assert.Same(expectedOutputFormatter, typedContent.Formatter);
                        Assert.NotNull(typedContent.Headers);
                        Assert.Equal(expectedMediaType, typedContent.Headers.ContentType);
                        Assert.Same(expectedRequest, response.RequestMessage);
                    }
                }
            }
        }
        public void ExecuteAsync_ReturnsCorrectResponse_WhenContentNegotiationSucceedsAndIncludeErrorDetailIsFalse()
        {
            // Arrange
            ModelStateDictionary modelState = CreateModelState();
            string expectedModelStateKey = "ModelStateKey";
            string expectedModelStateErrorMessage = "ModelStateErrorMessage";
            ModelState originalModelStateItem = new ModelState();
            originalModelStateItem.Errors.Add(new ModelError(new InvalidOperationException(),
                expectedModelStateErrorMessage));
            modelState.Add(expectedModelStateKey, originalModelStateItem);
            bool includeErrorDetail = false;
            MediaTypeFormatter expectedFormatter = CreateFormatter();
            MediaTypeHeaderValue expectedMediaType = CreateMediaType();
            ContentNegotiationResult negotiationResult = new ContentNegotiationResult(expectedFormatter,
                expectedMediaType);

            using (HttpRequestMessage expectedRequest = CreateRequest())
            {
                IEnumerable<MediaTypeFormatter> expectedFormatters = CreateFormatters();

                Mock<IContentNegotiator> spy = new Mock<IContentNegotiator>();
                spy.Setup(n => n.Negotiate(typeof(HttpError), expectedRequest, expectedFormatters)).Returns(
                    negotiationResult);
                IContentNegotiator contentNegotiator = spy.Object;

                IHttpActionResult result = CreateProductUnderTest(modelState, includeErrorDetail, contentNegotiator,
                    expectedRequest, expectedFormatters);

                // Act
                Task<HttpResponseMessage> task = result.ExecuteAsync(CancellationToken.None);

                // Assert
                Assert.NotNull(task);
                task.WaitUntilCompleted();

                using (HttpResponseMessage response = task.Result)
                {
                    Assert.NotNull(response);
                    Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
                    HttpContent content = response.Content;
                    Assert.IsType<ObjectContent<HttpError>>(content);
                    ObjectContent<HttpError> typedContent = (ObjectContent<HttpError>)content;
                    HttpError error = (HttpError)typedContent.Value;
                    Assert.NotNull(error);
                    HttpError modelStateError = error.ModelState;
                    Assert.NotNull(modelStateError);
                    Assert.True(modelState.ContainsKey(expectedModelStateKey));
                    object modelStateValue = modelStateError[expectedModelStateKey];
                    Assert.IsType(typeof(string[]), modelStateValue);
                    string[] typedModelStateValue = (string[])modelStateValue;
                    Assert.Equal(1, typedModelStateValue.Length);
                    Assert.Same(expectedModelStateErrorMessage, typedModelStateValue[0]);
                    Assert.Same(expectedFormatter, typedContent.Formatter);
                    Assert.NotNull(typedContent.Headers);
                    Assert.Equal(expectedMediaType, typedContent.Headers.ContentType);
                    Assert.Same(expectedRequest, response.RequestMessage);
                }
            }
        }
        public void ExecuteAsync_ForApiController_ReturnsCorrectResponse_WhenContentNegotationSucceeds()
        {
            // Arrange
            Exception expectedException = CreateExceptionWithStackTrace();
            ApiController controller = CreateController();
            MediaTypeFormatter expectedInputFormatter = CreateFormatter();
            MediaTypeFormatter expectedOutputFormatter = CreateFormatter();
            MediaTypeHeaderValue expectedMediaType = CreateMediaType();
            ContentNegotiationResult negotiationResult = new ContentNegotiationResult(expectedOutputFormatter,
                expectedMediaType);

            Expression<Func<IEnumerable<MediaTypeFormatter>, bool>> formattersMatch = (f) =>
                f != null && f.AsArray().Length == 1 && f.AsArray()[0] == expectedInputFormatter;

            using (HttpRequestMessage expectedRequest = CreateRequest())
            {
                Mock<IContentNegotiator> spy = new Mock<IContentNegotiator>();
                spy.Setup(n => n.Negotiate(typeof(HttpError), expectedRequest, It.Is(formattersMatch))).Returns(
                    negotiationResult);
                IContentNegotiator contentNegotiator = spy.Object;

                using (HttpConfiguration configuration = CreateConfiguration(expectedInputFormatter,
                    contentNegotiator))
                {
                    controller.RequestContext = new HttpRequestContext
                    {
                        Configuration = configuration,
                        IncludeErrorDetail = true
                    };
                    controller.Request = expectedRequest;

                    IHttpActionResult result = CreateProductUnderTest(expectedException, controller);

                    // Act
                    Task<HttpResponseMessage> task = result.ExecuteAsync(CancellationToken.None);

                    // Assert
                    Assert.NotNull(task);
                    task.WaitUntilCompleted();

                    using (HttpResponseMessage response = task.Result)
                    {
                        Assert.NotNull(response);
                        Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);
                        HttpContent content = response.Content;
                        Assert.IsType<ObjectContent<HttpError>>(content);
                        ObjectContent<HttpError> typedContent = (ObjectContent<HttpError>)content;
                        HttpError error = (HttpError)typedContent.Value;
                        Assert.NotNull(error);
                        Assert.Equal(expectedException.Message, error.ExceptionMessage);
                        Assert.Same(expectedException.GetType().FullName, error.ExceptionType);
                        Assert.Equal(expectedException.StackTrace, error.StackTrace);
                        Assert.Same(expectedOutputFormatter, typedContent.Formatter);
                        Assert.NotNull(typedContent.Headers);
                        Assert.Equal(expectedMediaType, typedContent.Headers.ContentType);
                        Assert.Same(expectedRequest, response.RequestMessage);
                    }
                }
            }
        }
        public void ExecuteAsync_ReturnsCorrectResponse_WhenContentNegotiationSucceedsAndIncludeErrorDetailIsFalse()
        {
            // Arrange
            Exception exception = CreateExceptionWithStackTrace();
            bool includeErrorDetail = false;
            MediaTypeFormatter expectedFormatter = CreateFormatter();
            MediaTypeHeaderValue expectedMediaType = CreateMediaType();
            ContentNegotiationResult negotiationResult = new ContentNegotiationResult(expectedFormatter,
                expectedMediaType);

            using (HttpRequestMessage expectedRequest = CreateRequest())
            {
                IEnumerable<MediaTypeFormatter> expectedFormatters = CreateFormatters();

                Mock<IContentNegotiator> spy = new Mock<IContentNegotiator>();
                spy.Setup(n => n.Negotiate(typeof(HttpError), expectedRequest, expectedFormatters)).Returns(
                    negotiationResult);
                IContentNegotiator contentNegotiator = spy.Object;

                IHttpActionResult result = CreateProductUnderTest(exception, includeErrorDetail, contentNegotiator,
                    expectedRequest, expectedFormatters);

                // Act
                Task<HttpResponseMessage> task = result.ExecuteAsync(CancellationToken.None);

                // Assert
                Assert.NotNull(task);
                task.WaitUntilCompleted();

                using (HttpResponseMessage response = task.Result)
                {
                    Assert.NotNull(response);
                    Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);
                    HttpContent content = response.Content;
                    Assert.IsType<ObjectContent<HttpError>>(content);
                    ObjectContent<HttpError> typedContent = (ObjectContent<HttpError>)content;
                    HttpError error = (HttpError)typedContent.Value;
                    Assert.NotNull(error);
                    Assert.Null(error.ExceptionMessage);
                    Assert.Null(error.ExceptionType);
                    Assert.Null(error.StackTrace);
                    Assert.Same(expectedFormatter, typedContent.Formatter);
                    Assert.NotNull(typedContent.Headers);
                    Assert.Equal(expectedMediaType, typedContent.Headers.ContentType);
                    Assert.Same(expectedRequest, response.RequestMessage);
                }
            }
        }
 /// <summary>
 /// Performs content negotiating by selecting the most appropriate <see cref="T:System.Net.Http.Formatting.MediaTypeFormatter" /> out of the passed in formatters for the given request that can serialize an object of the given type.
 /// </summary>
 /// <param name="type">The type to be serialized.</param>
 /// <param name="request">Request message, which contains the header values used to perform negotiation.</param>
 /// <param name="formatters">The set of <see cref="T:System.Net.Http.Formatting.MediaTypeFormatter" /> objects from which to choose.</param>
 public ContentNegotiationResult Negotiate(Type type, HttpRequestMessage request, IEnumerable<MediaTypeFormatter> formatters)
 {
     var result = new ContentNegotiationResult(this._formatter, new MediaTypeHeaderValue(Constants.HttpApi.ContentType));
     return result;
 }
        public void ExecuteAsync_Throws_WhenUrlHelperLinkReturnsNull_AfterContentNegotiationSucceeds()
        {
            // Arrange
            string expectedRouteName = CreateRouteName();
            IDictionary<string, object> expectedRouteValues = CreateRouteValues();
            object expectedContent = CreateContent();
            Mock<UrlHelper> stubUrlFactory = new Mock<UrlHelper>(MockBehavior.Strict);
            stubUrlFactory.Setup(f => f.Link(expectedRouteName, expectedRouteValues)).Returns((string)null);
            UrlHelper urlFactory = stubUrlFactory.Object;
            MediaTypeFormatter expectedFormatter = CreateFormatter();
            MediaTypeHeaderValue expectedMediaType = CreateMediaType();
            ContentNegotiationResult negotiationResult = new ContentNegotiationResult(expectedFormatter,
                expectedMediaType);

            using (HttpRequestMessage expectedRequest = CreateRequest())
            {
                IEnumerable<MediaTypeFormatter> expectedFormatters = CreateFormatters();

                Mock<IContentNegotiator> spyContentNegotiator = new Mock<IContentNegotiator>();
                spyContentNegotiator.Setup(n => n.Negotiate(typeof(object), expectedRequest, expectedFormatters))
                    .Returns(negotiationResult);
                IContentNegotiator contentNegotiator = spyContentNegotiator.Object;

                IHttpActionResult result = CreateProductUnderTest(expectedRouteName, expectedRouteValues,
                    expectedContent, urlFactory, contentNegotiator, expectedRequest, expectedFormatters);

                // Act & Assert
                InvalidOperationException exception = Assert.Throws<InvalidOperationException>(() =>
                    {
                        HttpResponseMessage ignore = result.ExecuteAsync(CancellationToken.None).Result;
                    });
                Assert.Equal("UrlHelper.Link must not return null.", exception.Message);
            }
        }