コード例 #1
0
        public HttpResponseMessage Get()
        {
            #region Please modify the code to pass the test

            // Please note that you may have to run this program in IIS or IISExpress first in
            // order to pass the test.
            // You can add new files if you want. But you cannot change any existed code.

            IContentNegotiator       contentNegotiator = Configuration.Services.GetContentNegotiator();
            ContentNegotiationResult result            = contentNegotiator.Negotiate(typeof(MessageDto), Request, Configuration.Formatters);

            if (result == null)
            {
                var response = new HttpResponseMessage(HttpStatusCode.NotAcceptable);
                throw new HttpResponseException(response);
            }

            return(new HttpResponseMessage
            {
                Content = new ObjectContent <MessageDto>(
                    new MessageDto {
                    Message = "Hello"
                },
                    result.Formatter,
                    result.MediaType.MediaType)
            });

            #endregion
        }
コード例 #2
0
        public override void OnException(HttpActionExecutedContext context)
        {
            var errors = new ErrorModel();
            var ex     = context.Exception;

            do
            {
                if (ex is NotImplementedException)
                {
                    errors.Errors.Add(new ErrorDetailModel
                    {
                        Code        = HttpStatusCode.NotImplemented,
                        Description = "Service Provider does not support the request operation"
                    });
                }
                else if (ex is ScimException)
                {
                    errors.Errors.Add(new ErrorDetailModel
                    {
                        Code        = ((ScimException)ex).StatusCode,
                        Description = ex.Message
                    });
                }
                ex = ex.InnerException;
            } while (ex != null);


            IContentNegotiator       negotiator = GlobalConfiguration.Configuration.Services.GetContentNegotiator();
            ContentNegotiationResult result     = negotiator.Negotiate(typeof(ErrorModel), context.Request, GlobalConfiguration.Configuration.Formatters);

            context.Response = new HttpResponseMessage(errors.Errors[0].Code)
            {
                Content = new ObjectContent <ErrorModel>(errors, result.Formatter, result.MediaType.MediaType)
            };
        }
コード例 #3
0
        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.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);
                        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);
                    }
                }
            }
        }
コード例 #4
0
        public HttpResponseMessage Get(HttpRequestMessage request)
        {
            var config = request.GetConfiguration();

            // The IContentNegotiator instance is registered with
            // the HttpConfiguration. By default, it uses an instance
            // of DefaultContentNegotiator.
            IContentNegotiator negotiator = config.Services.GetContentNegotiator();

            // Negotiate takes the type, the request, and the formatters you
            // wish to use. By default, Web API inserts the JsonMediaTypeFormatter
            // and XmlMediaTypeFormatter, in that order.
            ContentNegotiationResult result =
                negotiator.Negotiate(typeof(Helpers.FILL_ME_IN), request, config.Formatters);

            var person = new Person {
                FirstName = "Ryan", LastName = "Riley"
            };

            // Use the ContentNegotiationResult with an ObjectContent to format the object.
            var content = new ObjectContent <Person>(person, result.Formatter, result.MediaType);

            return(new HttpResponseMessage {
                Content = content
            });
        }
コード例 #5
0
        public void ExecuteAsync_Returns_CorrectResponse_WhenContentNegotiationFails()
        {
            // Arrange
            Uri    location = CreateLocation();
            object content  = CreateContent();
            ContentNegotiationResult negotiationResult = null;

            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(location, content, 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.NotAcceptable, response.StatusCode);
                    Assert.Null(response.Headers.Location);
                    Assert.Same(expectedRequest, response.RequestMessage);
                }
            }
        }
コード例 #6
0
            public ContentNegotiationResult Negotiate(Type type, HttpRequestMessage request, IEnumerable <MediaTypeFormatter> formatters)
            {
                // Only allow json content
                var result = new ContentNegotiationResult(_jsonFormatter, new MediaTypeHeaderValue("application/json"));

                return(result);
            }
コード例 #7
0
        public void ExecuteAsync_ReturnsCorrectResponse_WhenContentNegotiationFails()
        {
            // Arrange
            ModelStateDictionary modelState            = CreateModelStateWithError();
            bool includeErrorDetail                    = true;
            ContentNegotiationResult negotiationResult = null;

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

                Mock <IContentNegotiator> spy = new Mock <IContentNegotiator>();
                spy.Setup(n => n.Negotiate(typeof(ModelStateDictionary), 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.NotAcceptable, response.StatusCode);
                    Assert.Same(expectedRequest, response.RequestMessage);
                }
            }
        }
コード例 #8
0
        public HttpResponseMessage GetGizmoDog()
        {
            var dog = new Dog()
            {
                name = "Gizmo"
            };

            IContentNegotiator negotiator = this.Configuration.Services.GetContentNegotiator();

            ContentNegotiationResult result = negotiator.Negotiate(
                typeof(Dog), this.Request, this.Configuration.Formatters);

            if (result == null)
            {
                var response = new HttpResponseMessage(HttpStatusCode.NotAcceptable);
                throw new HttpResponseException(response);
            }

            return(new HttpResponseMessage()
            {
                Content = new ObjectContent <Dog>(
                    dog,                       // What we are serializing
                    result.Formatter,          // The media formatter
                    result.MediaType.MediaType // The MIME type
                    )
            });
        }
コード例 #9
0
        public ContentNegotiationResult Negotiate(Type type, HttpRequestMessage request,
                                                  IEnumerable <MediaTypeFormatter> formatters)
        {
            var result = new ContentNegotiationResult(_jsonFormatter, new System.Net.Http.Headers.MediaTypeHeaderValue("application/json"));

            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);
            }
        }
コード例 #11
0
        public HttpResponseMessage Get()
        {
            var users = _usersDomain.GetAll();

            var usersDto = _mapper.Map <IEnumerable <Entity.User>, IEnumerable <UserDto> >(users);

            IContentNegotiator negotiator = Configuration.Services.GetContentNegotiator();

            ContentNegotiationResult result = negotiator.Negotiate(
                usersDto.GetType(), Request, Configuration.Formatters);

            if (result == null)
            {
                var response = new HttpResponseMessage(HttpStatusCode.NotAcceptable);
                throw new HttpResponseException(response);
            }

            return(new HttpResponseMessage()
            {
                Content = new ObjectContent <IEnumerable <UserDto> >(
                    usersDto,
                    result.Formatter,
                    result.MediaType.MediaType
                    )
            });
        }
コード例 #12
0
        /// <summary>
        /// Runs the controller action within a mocked HTTP context
        /// </summary>
        /// <typeparam name="T">The controller type</typeparam>
        /// <typeparam name="TReturn">The controller action return type</typeparam>
        /// <param name="controller"></param>
        /// <param name="func">The controller code to execute within a mocked HTTP context</param>
        /// <returns>The HttpResponseMessage containing the action result</returns>
        public static async Task <HttpResponseMessage> WithMockedHttpRequest <T, TReturn>(
            this T controller, Func <T, Task <TReturn> > func) where T : ApiController
        {
            // Build a mocked JSON request/response configuration
            MediaTypeFormatter        expectedFormatter = new StubMediaTypeFormatter();
            MediaTypeHeaderValue      expectedMediaType = new MediaTypeHeaderValue("text/json");
            ContentNegotiationResult  negotiationResult = new ContentNegotiationResult(expectedFormatter, expectedMediaType);
            Mock <IContentNegotiator> contentNegotiator = new Mock <IContentNegotiator>();

            contentNegotiator
            .Setup(n => n.Negotiate(It.IsAny <Type>(), It.IsAny <HttpRequestMessage>(), It.IsAny <IEnumerable <MediaTypeFormatter> >()))
            .Returns(negotiationResult);
            using (HttpConfiguration configuration = CreateConfiguration(new StubMediaTypeFormatter(), contentNegotiator.Object))
            {
                controller.Configuration = configuration;
                // Build a mocked request context from which to build the response
                using (HttpRequestMessage request = new HttpRequestMessage())
                {
                    controller.Request = request;
                    var actionResult = await func.Invoke(controller);

                    // Create the response from the action result
                    if (typeof(IHttpActionResult).IsAssignableFrom(typeof(TReturn)))
                    {
                        return(await((IHttpActionResult)actionResult).ExecuteAsync(CancellationToken.None));
                    }
                    else
                    {
                        return(await Task.FromResult(request.CreateResponse(actionResult)));
                    }
                }
            }
        }
コード例 #13
0
        public async Task ExecuteAsync_ForApiController_ReturnsCorrectResponse_WhenContentNegotationSucceeds()
        {
            // Arrange
            string expectedRouteName = CreateRouteName();
            IDictionary <string, object> expectedRouteValues = CreateRouteValues();
            object           expectedContent  = CreateContent();
            Mock <UrlHelper> spyUrlFactory    = new Mock <UrlHelper>(MockBehavior.Strict);
            string           expectedLocation = CreateLocation().AbsoluteUri;

            spyUrlFactory.Setup(f => f.Link(expectedRouteName, expectedRouteValues)).Returns(expectedLocation);
            UrlHelper                urlFactory              = spyUrlFactory.Object;
            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;
                    controller.Url           = urlFactory;

                    IHttpActionResult result = CreateProductUnderTest(expectedRouteName, expectedRouteValues,
                                                                      expectedContent, controller);

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

                    // Assert
                    Assert.NotNull(task);

                    using (HttpResponseMessage response = await task)
                    {
                        Assert.NotNull(response);
                        Assert.Equal(HttpStatusCode.Created, response.StatusCode);
                        Assert.Same(expectedLocation, response.Headers.Location.OriginalString);
                        HttpContent            content      = response.Content;
                        ObjectContent <object> typedContent = Assert.IsType <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);
                    }
                }
            }
        }
コード例 #14
0
        public HttpResponseMessage GetProduct(int id)
        {
            var product = new Product()
            {
                Id = id, Name = "Gizmo", Category = "Widgets", Price = 1.99M
            };

            IContentNegotiator negotiator = this.Configuration.Services.GetContentNegotiator();

            ContentNegotiationResult result = negotiator.Negotiate(
                typeof(Product), this.Request, this.Configuration.Formatters);

            if (result == null)
            {
                var response = new HttpResponseMessage(HttpStatusCode.NotAcceptable);
                throw new HttpResponseException(response);
            }

            return(new HttpResponseMessage()
            {
                Content = new ObjectContent <Product>(
                    product,                   // What we are serializing
                    result.Formatter,          // The media formatter
                    result.MediaType.MediaType // The MIME type
                    )
            });
            // This code is equivalent to the what the pipeline does automatically.
        }
コード例 #15
0
        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);
                }
            }
        }
コード例 #16
0
ファイル: GroupsController.cs プロジェクト: EdinPa/SCIM.net
        public HttpResponseMessage Get(Guid id)
        {
            var group = Uow.Groups.GetById(id);

            if (group == null)
            {
                throw new ScimException(HttpStatusCode.NotFound, string.Format("Resource {0} not found", id));
            }


            IContentNegotiator       negotiator = this.Configuration.Services.GetContentNegotiator();
            ContentNegotiationResult result     = negotiator.Negotiate(typeof(UserModel), this.Request, this.Configuration.Formatters);

            if (result == null)
            {
                throw new ScimException(HttpStatusCode.NotAcceptable, "Server does not support requested operation");
            }


            return(new HttpResponseMessage()
            {
                Content = new ObjectContent <GroupModel>(
                    group,                     // What we are serializing
                    result.Formatter,          // The media formatter
                    result.MediaType.MediaType // The MIME type
                    )
            });
        }
コード例 #17
0
        private HttpResponseMessage Execute()
        {
            // Run content negotiation.
            ContentNegotiationResult result = _dependencies.ContentNegotiator.Negotiate(typeof(T),
                                                                                        _dependencies.Request, _dependencies.Formatters);

            HttpResponseMessage response = new HttpResponseMessage();

            try
            {
                if (result == null)
                {
                    // A null result from content negotiation indicates that the response should be a 406.
                    response.StatusCode = HttpStatusCode.NotAcceptable;
                }
                else
                {
                    response.StatusCode       = HttpStatusCode.Created;
                    response.Headers.Location = _location;
                    Contract.Assert(result.Formatter != null);
                    // At this point mediaType should be a cloned value. (The content negotiator is responsible for
                    // returning a new copy.)
                    response.Content = new ObjectContent <T>(_content, result.Formatter, result.MediaType);
                }

                response.RequestMessage = _dependencies.Request;
            }
            catch
            {
                response.Dispose();
                throw;
            }

            return(response);
        }
        public async Task ExecuteAsync_ReturnsCorrectResponse_WhenContentNegotiationFails()
        {
            // Arrange
            string message = CreateMessage();
            ContentNegotiationResult negotiationResult = null;

            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(message, contentNegotiator, expectedRequest,
                                                                  expectedFormatters);

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

                // Assert
                Assert.NotNull(task);

                using (HttpResponseMessage response = await task)
                {
                    Assert.NotNull(response);
                    Assert.Equal(HttpStatusCode.NotAcceptable, response.StatusCode);
                    Assert.Same(expectedRequest, response.RequestMessage);
                }
            }
        }
コード例 #19
0
        public static HttpResponseMessage CreateResponse(this HttpRequestMessage request, HttpStatusCode statusCode, object value, Type type)
        {
            var configuration = request.GetConfiguration();
            IContentNegotiator contentNegotiator        = configuration.Services.GetContentNegotiator();
            IEnumerable <MediaTypeFormatter> formatters = configuration.Formatters;

            // Run content negotiation
            ContentNegotiationResult result = contentNegotiator.Negotiate(type, request, formatters);

            if (result == null)
            {
                // no result from content negotiation indicates that 406 should be sent.
                return(new HttpResponseMessage
                {
                    StatusCode = HttpStatusCode.NotAcceptable,
                    RequestMessage = request,
                });
            }
            else
            {
                MediaTypeHeaderValue mediaType = result.MediaType;
                return(new HttpResponseMessage
                {
                    // At this point mediaType should be a cloned value (the content negotiator is responsible for returning a new copy)
                    Content = new ObjectContent(type, value, result.Formatter, mediaType),
                    StatusCode = statusCode,
                    RequestMessage = request
                });
            }
        }
コード例 #20
0
        /// <inheritdoc />
        protected override async Task WriteContent(HttpResponseMessage response, Stream stream, HttpContent content, TransportContext context, CancellationToken token = default(CancellationToken))
        {
            if (token.IsCancellationRequested)
            {
                return;
            }

            IEnumerable enumerable = GetResultFunction();

            if (enumerable == null || token.IsCancellationRequested)
            {
                return;
            }

            HttpConfiguration configuration = Request.GetConfiguration();

            if (configuration == null)
            {
                throw new HttpConfigurationMissingException();
            }

            Type type = enumerable.GetType();
            ContentNegotiationResult result = configuration.Services
                                              .GetContentNegotiator()?
                                              .Negotiate(type, Request, configuration.Formatters);

            if (result == null || token.IsCancellationRequested)
            {
                return;
            }
            await result.Formatter.WriteToStreamAsync(type, enumerable, stream, content, context, token);
        }
コード例 #21
0
        public ContentNegotiationResult Negotiate(Type type, HttpRequestMessage request,
                                                  IEnumerable <MediaTypeFormatter> formatters)
        {
            var result = new ContentNegotiationResult(new JsonMediaTypeFormatter(),
                                                      new MediaTypeHeaderValue("application/json"));

            return(result);
        }
コード例 #22
0
        public static ContentNegotiationResult FindContentNegotiation(HttpRequestMessage request)
        {
            IContentNegotiator       negotiator = GlobalConfiguration.Configuration.Services.GetContentNegotiator();
            ContentNegotiationResult result     = negotiator.Negotiate(
                typeof(SDataDiagnosis), request, GlobalConfiguration.Configuration.Formatters);

            return(result);
        }
コード例 #23
0
        private HttpContent ContentFor(
            HttpRequestMessage request,
            SwaggerDocument swaggerDoc)
        {
            ContentNegotiationResult negotiationResult = ServicesExtensions.GetContentNegotiator(HttpRequestMessageExtensions.GetConfiguration(request).get_Services()).Negotiate(typeof(SwaggerDocument), request, this.GetSupportedSwaggerFormatters());

            return((HttpContent) new ObjectContent(typeof(SwaggerDocument), (object)swaggerDoc, negotiationResult.get_Formatter(), negotiationResult.get_MediaType()));
        }
コード例 #24
0
        public Task <HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
        {
            IContentNegotiator       negotiator = configuration.Services.GetContentNegotiator();
            ContentNegotiationResult result     = negotiator.Negotiate(typeof(T), request, configuration.Formatters);
            HttpResponseMessage      response   = new HttpResponseMessage(HttpStatusCode.OK);

            response.Content = new ObjectContent(typeof(T), Content, result.Formatter);
            return(Task.FromResult <HttpResponseMessage>(response));
        }
コード例 #25
0
        public async Task 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);

                using (HttpResponseMessage response = await task)
                {
                    Assert.NotNull(response);
                    Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);
                    HttpContent content = response.Content;
                    ObjectContent <HttpError> typedContent = Assert.IsType <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);
                }
            }
        }
コード例 #26
0
        protected override Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            ContentNegotiationResult result = _contentNegotiator.Negotiate(_mediaTypeFormatters, request.Headers.Accept);

            if (result == null)
            {
                return(Task <HttpResponseMessage> .Factory.StartNew(() => new HttpResponseMessage(HttpStatusCode.NotAcceptable)));
            }

            return(base.SendAsync(request, cancellationToken));
        }
コード例 #27
0
        public ContentNegotiationResult Negotiate(
            Type type,
            HttpRequestMessage request,
            IEnumerable <MediaTypeFormatter> formatters
            )
        {
            ContentNegotiationResult result = null;

            _traceWriter.TraceBeginEnd(
                request,
                TraceCategories.FormattingCategory,
                TraceLevel.Info,
                _innerNegotiator.GetType().Name,
                NegotiateMethodName,
                beginTrace: (tr) =>
            {
                tr.Message = Error.Format(
                    SRResources.TraceNegotiateFormatter,
                    type.Name,
                    FormattingUtilities.FormattersToString(formatters)
                    );
            },
                execute: () =>
            {
                result = _innerNegotiator.Negotiate(type, request, formatters);
            },
                endTrace: (tr) =>
            {
                tr.Message = Error.Format(
                    SRResources.TraceSelectedFormatter,
                    result == null
                          ? SRResources.TraceNoneObjectMessage
                          : MediaTypeFormatterTracer
                    .ActualMediaTypeFormatter(result.Formatter)
                    .GetType().Name,
                    result == null || result.MediaType == null
                          ? SRResources.TraceNoneObjectMessage
                          : result.MediaType.ToString()
                    );
            },
                errorTrace: null
                );

            if (result != null)
            {
                result.Formatter = MediaTypeFormatterTracer.CreateTracer(
                    result.Formatter,
                    _traceWriter,
                    request
                    );
            }

            return(result);
        }
コード例 #28
0
        public void ExecuteAsync_ForApiController_ReturnsCorrectResponse_WhenContentNegotationSucceeds()
        {
            // Arrange
            HttpStatusCode           expectedStatusCode      = CreateStatusCode();
            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 = new NegotiatedContentResult <object>(expectedStatusCode, 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(expectedStatusCode, response.StatusCode);
                        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);
                    }
                }
            }
        }
コード例 #29
0
        private void SetFormatter()
        {
            IContentNegotiator       negotiator = this.Configuration.Services.GetContentNegotiator();
            ContentNegotiationResult result     = negotiator.Negotiate(typeof(MoviesList), this.Request, this.Configuration.Formatters);

            if (result == null)
            {
                var response = new HttpResponseMessage(HttpStatusCode.NotAcceptable);
                throw new HttpResponseException(response);
            }
        }
コード例 #30
0
        public ContentNegotiationResult Negotiate(
            Type type,
            HttpRequestMessage request,
            IEnumerable <MediaTypeFormatter> formatters)
        {
            // no complex logic. always return the json formatter
            var result = new ContentNegotiationResult(_jsonFormatter,
                                                      new MediaTypeHeaderValue("application/json"));

            return(result);
        }