public void NegotiateBy(IContentNegotiator negotiator) { if (negotiator == null) throw new ArgumentNullException(nameof(negotiator)); _negotiator = negotiator; }
public ActionInvokerComponent(AppFunc next, MediaTypeFormatterCollection formatters, IContentNegotiator contentNegotiator, IActionParameterBinder parameterBinder) { _next = next; _formatters = formatters; _contentNegotiator = contentNegotiator; _actionParameterBinder = parameterBinder; }
/// <summary>Initializes a new instance of the <see cref="InvalidModelStateResult"/> class.</summary> /// <param name="modelState">The model state to include in the error.</param> /// <param name="includeErrorDetail"> /// <see langword="true"/> if the error should include exception messages; otherwise, <see langword="false"/>. /// </param> /// <param name="contentNegotiator">The content negotiator to handle content negotiation.</param> /// <param name="request">The request message which led to this result.</param> /// <param name="formatters">The formatters to use to negotiate and format the content.</param> public InvalidModelStateResult(ModelStateDictionary modelState, bool includeErrorDetail, IContentNegotiator contentNegotiator, HttpRequestMessage request, IEnumerable<MediaTypeFormatter> formatters) : this(modelState, new ExceptionResult.DirectDependencyProvider(includeErrorDetail, contentNegotiator, request, formatters)) { }
private IHttpActionResult GetExceptionActionResult( Exception exception, bool includeErrorDetail, IContentNegotiator contentNegotiator, HttpRequestMessage request, IEnumerable<MediaTypeFormatter> formatters) { // Add a ReferenceId property to the exception so we can log it and/or return it to the caller. exception.AddReferenceId(); if (exception is NotAuthorizedException) return new StatusCodeResult(HttpStatusCode.Unauthorized, request); if (exception is ForbiddenException) return new StatusCodeResult(HttpStatusCode.Forbidden, request); var validationException = exception as ValidationException; if (validationException != null) return new ValidationExceptionResult(validationException, includeErrorDetail, contentNegotiator, request, formatters); if (exception is DuplicateException) return new ConflictResult(request); if (exception is NotFoundException) return new NotFoundResult(request); _logger.Error(exception, "Received exception while processing request.\n{0}", request.RequestUri); var unavailableException = exception as ServiceUnavailableException; if (unavailableException != null) return new ServiceUnavailableExceptionResult( unavailableException, includeErrorDetail, contentNegotiator, request, formatters); return new ReferencedExceptionResult(exception, includeErrorDetail, contentNegotiator, request, formatters); }
public NotAcceptableMessageHandler(HttpConfiguration configuration) { if (configuration == null) throw new ArgumentNullException("configuration"); this.contentNegotiator = configuration.Services.GetContentNegotiator(); this.mediaTypeFormatters = configuration.Formatters; }
public ContentNegotiatorTracer(IContentNegotiator innerNegotiator, ITraceWriter traceWriter) { Contract.Assert(innerNegotiator != null); Contract.Assert(traceWriter != null); _innerNegotiator = innerNegotiator; _traceWriter = traceWriter; }
/// <summary>Initializes a new instance of the <see cref="InvalidModelStateResult"/> class.</summary> /// <param name="exception">The ServiceUnavailable exception information to include in the error.</param> /// <param name="includeErrorDetail"> /// <see langword="true"/> if the error should include exception messages; otherwise, <see langword="false"/>. /// </param> /// <param name="contentNegotiator">The content negotiator to handle content negotiation.</param> /// <param name="request">The request message which led to this result.</param> /// <param name="formatters">The formatters to use to negotiate and format the content.</param> public ServiceUnavailableExceptionResult( ServiceUnavailableException exception, bool includeErrorDetail, IContentNegotiator contentNegotiator, HttpRequestMessage request, IEnumerable<MediaTypeFormatter> formatters) : this(exception, new DirectDependencyProvider(includeErrorDetail, contentNegotiator, request, formatters)) { }
/// <summary> /// Initializes a new instance of the <see cref="ResultWrapper"/> class with the provided content negotiator. /// </summary> /// <param name="contentNegotiator">The content negotiator.</param> public ResultWrapper(IContentNegotiator contentNegotiator) { if (contentNegotiator == null) { throw new ArgumentNullException("contentNegotiator"); } m_contentNegotiator = contentNegotiator; }
public PerRequestContentNegotiator(IContentNegotiator innerContentNegotiator) { if (innerContentNegotiator == null) { throw Error.ArgumentNull("innerContentNegotiator"); } _innerContentNegotiator = innerContentNegotiator; }
/// <summary> /// Initializes a new instance of the <see cref="ContentResult"/> class with the provided content negotiator. /// </summary> /// <param name="contentNegotiator">The content negotiator.</param> public ContentResult(IContentNegotiator contentNegotiator) { if (contentNegotiator == null) { throw new ArgumentNullException("contentNegotiator"); } m_contentNegotiator = contentNegotiator; ClearOutput = true; }
public NotAcceptableMessageHandler(HttpConfiguration configuration, HttpMessageHandler innerHandler) : base(innerHandler) { if (configuration == null) { throw new ArgumentNullException("configuration"); } _contentNegotiator = configuration.Services.GetContentNegotiator(); _mediaTypeFormatters = configuration.Formatters; }
/// <summary> /// Initializes a new instance of the <see cref="StreamResult"/> class with the provided content negotiator. /// </summary> /// <param name="contentNegotiator">The content negotiator.</param> public StreamResult(IContentNegotiator contentNegotiator) { if (contentNegotiator == null) { throw new ArgumentNullException("contentNegotiator"); } m_contentNegotiator = contentNegotiator; m_buffer = DefaultBuffer; ClearOutput = true; }
public BrowserRouteConstraint(IContentNegotiator contentNegotiator, IHttpRequest request) { if (contentNegotiator == null) { throw new ArgumentNullException("contentNegotiator"); } if (request == null) { throw new ArgumentNullException("request"); } m_contentNegotiator = contentNegotiator; m_request = request; }
/// <summary> /// Validates the IContentNegotiator from action result containing one. /// </summary> /// <param name="actionResult">Action result with IContentNegotiator.</param> /// <param name="contentNegotiator">Expected IContentNegotiator.</param> /// <param name="failedValidationAction">Action to call in case of failed validation.</param> public static void ValidateContentNegotiator( dynamic actionResult, IContentNegotiator contentNegotiator, Action<string, string, string> failedValidationAction) { RuntimeBinderValidator.ValidateBinding(() => { var actualContentNegotiator = actionResult.ContentNegotiator as IContentNegotiator; if (Reflection.AreDifferentTypes(contentNegotiator, actualContentNegotiator)) { failedValidationAction( "IContentNegotiator", string.Format("to be {0}", contentNegotiator.GetName()), string.Format("instead received {0}", actualContentNegotiator.GetName())); } }); }
public void ContentNegotiator_ForApiController_Throws_WhenConfigurationIsNull() { // Arrange Uri location = CreateLocation(); object content = CreateContent(); ApiController controller = CreateController(); HttpControllerContext context = new HttpControllerContext(); using (HttpRequestMessage request = CreateRequest()) { controller.ControllerContext = context; CreatedNegotiatedContentResult <object> result = CreateProductUnderTest(location, content, controller); // Act & Assert Assert.Throws <InvalidOperationException>( () => { IContentNegotiator ignore = result.ContentNegotiator; }, "HttpControllerContext.Configuration must not be null."); } }
public void ContentNegotiator_ForApiController_Throws_WhenServiceIsNull() { // Arrange object content = CreateContent(); ApiController controller = CreateController(); using (HttpConfiguration configuration = CreateConfiguration(CreateFormatter(), null)) using (HttpRequestMessage request = CreateRequest()) { controller.Configuration = configuration; OkNegotiatedContentResult <object> result = CreateProductUnderTest(content, controller); // Act & Assert Assert.Throws <InvalidOperationException>( () => { IContentNegotiator ignore = result.ContentNegotiator; }, "The provided configuration does not have an instance of the " + "'System.Net.Http.Formatting.IContentNegotiator' service registered."); } }
public void ContentNegotiator_Returns_InstanceProvided() { // Arrange object content = CreateContent(); IContentNegotiator expectedContentNegotiator = CreateContentNegotiator(); using (HttpRequestMessage request = CreateRequest()) { IEnumerable <MediaTypeFormatter> formatters = CreateFormatters(); OkNegotiatedContentResult <object> result = CreateProductUnderTest(content, expectedContentNegotiator, request, formatters); // Act IContentNegotiator contentNegotiator = result.ContentNegotiator; // Assert Assert.Same(expectedContentNegotiator, contentNegotiator); } }
public void ContentNegotiator_ForApiController_EvaluatesOnce() { // Arrange string routeName = CreateRouteName(); IDictionary <string, object> routeValues = CreateRouteValues(); object content = CreateContent(); IContentNegotiator expectedContentNegotiator = CreateDummyContentNegotiator(); ApiController controller = CreateController(); using ( HttpConfiguration configuration = CreateConfiguration( CreateFormatter(), expectedContentNegotiator ) ) using (HttpRequestMessage request = CreateRequest()) { controller.Configuration = configuration; controller.Request = request; CreatedAtRouteNegotiatedContentResult <object> result = CreateProductUnderTest( routeName, routeValues, content, controller ); IContentNegotiator ignore = result.ContentNegotiator; configuration.Services.Replace( typeof(IContentNegotiator), CreateDummyContentNegotiator() ); // Act IContentNegotiator contentNegotiator = result.ContentNegotiator; // Assert Assert.Same(expectedContentNegotiator, contentNegotiator); } }
public void Formatters_ForApiController_EvaluatesLazily() { // Arrange Exception exception = CreateException(); ApiController controller = CreateController(); IContentNegotiator contentNegotiator = CreateDummyContentNegotiator(); using ( HttpConfiguration earlyConfiguration = CreateConfiguration( CreateFormatter(), contentNegotiator ) ) using (HttpRequestMessage request = CreateRequest()) { controller.Configuration = earlyConfiguration; controller.Request = request; ExceptionResult result = CreateProductUnderTest(exception, controller); MediaTypeFormatter expectedFormatter = CreateFormatter(); using ( HttpConfiguration lateConfiguration = CreateConfiguration( expectedFormatter, contentNegotiator ) ) { controller.Configuration = lateConfiguration; // Act IEnumerable <MediaTypeFormatter> formatters = result.Formatters; // Assert Assert.NotNull(formatters); MediaTypeFormatter formatter = Assert.Single(formatters); Assert.Same(expectedFormatter, formatter); } } }
public async Task ExecuteAsync_Returns_CorrectResponse_WhenContentNegotiationSucceeds() { // Arrange HttpStatusCode expectedStatusCode = CreateStatusCode(); 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 = new NegotiatedContentResult <object>(expectedStatusCode, expectedContent, 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(expectedStatusCode, response.StatusCode); HttpContent content = response.Content; ObjectContent <object> typedContent = Assert.IsType <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 Formatters_Returns_InstanceProvided() { // Arrange HttpStatusCode statusCode = CreateStatusCode(); object content = CreateContent(); IContentNegotiator contentNegotiator = CreateContentNegotiator(); using (HttpRequestMessage request = CreateRequest()) { IEnumerable <MediaTypeFormatter> expectedFormatters = CreateFormatters(); NegotiatedContentResult <object> result = new NegotiatedContentResult <object>(statusCode, content, contentNegotiator, request, expectedFormatters); // Act IEnumerable <MediaTypeFormatter> formatters = result.Formatters; // Assert Assert.Same(expectedFormatters, formatters); } }
public void Exception_ReturnsInstanceProvided() { // Arrange Exception expectedException = CreateException(); bool includeErrorDetail = true; IContentNegotiator contentNegotiator = CreateDummyContentNegotiator(); using (HttpRequestMessage request = CreateRequest()) { IEnumerable <MediaTypeFormatter> formatters = CreateFormatters(); ExceptionResult result = CreateProductUnderTest(expectedException, includeErrorDetail, contentNegotiator, request, formatters); // Act Exception exception = result.Exception; // Assert Assert.Same(expectedException, exception); } }
public void IncludeErrorDetail_ReturnsValueProvided() { // Arrange ModelStateDictionary modelState = CreateModelState(); bool expectedIncludeErrorDetail = true; IContentNegotiator contentNegotiator = CreateDummyContentNegotiator(); using (HttpRequestMessage request = CreateRequest()) { IEnumerable <MediaTypeFormatter> formatters = CreateFormatters(); InvalidModelStateResult result = CreateProductUnderTest(modelState, expectedIncludeErrorDetail, contentNegotiator, request, formatters); // Act bool includeErrorDetail = result.IncludeErrorDetail; // Assert Assert.Equal(expectedIncludeErrorDetail, includeErrorDetail); } }
public void ModelState_ReturnsInstanceProvided() { // Arrange ModelStateDictionary expectedModelState = CreateModelState(); bool includeErrorDetail = true; IContentNegotiator contentNegotiator = CreateDummyContentNegotiator(); using (HttpRequestMessage request = CreateRequest()) { IEnumerable <MediaTypeFormatter> formatters = CreateFormatters(); InvalidModelStateResult result = CreateProductUnderTest(expectedModelState, includeErrorDetail, contentNegotiator, request, formatters); // Act ModelStateDictionary modelState = result.ModelState; // Assert Assert.Same(expectedModelState, modelState); } }
public void StatusCode_Returns_ValueProvided() { // Arrange HttpStatusCode expectedStatusCode = CreateStatusCode(); object content = CreateContent(); IContentNegotiator contentNegotiator = CreateContentNegotiator(); using (HttpRequestMessage request = CreateRequest()) { IEnumerable <MediaTypeFormatter> formatters = CreateFormatters(); NegotiatedContentResult <object> result = new NegotiatedContentResult <object>(expectedStatusCode, content, contentNegotiator, request, formatters); // Act HttpStatusCode statusCode = result.StatusCode; // Assert Assert.Equal(expectedStatusCode, statusCode); } }
/// <summary> /// Initializes a new instance of the <see cref="RootRouteHandler"/> class. /// </summary> /// <param name="serviceContext">The service context.</param> /// <param name="contentNegotiator">The content negotiator.</param> /// <param name="resultWrapper">The service method result wrapper.</param> public RootRouteHandler(IServiceContext serviceContext, IContentNegotiator contentNegotiator, IResultWrapper resultWrapper) { if (serviceContext == null) { throw new ArgumentNullException("serviceContext"); } if (contentNegotiator == null) { throw new ArgumentNullException("contentNegotiator"); } if (resultWrapper == null) { throw new ArgumentNullException("resultWrapper"); } m_serviceContext = serviceContext; m_contentNegotiator = contentNegotiator; m_resultWrapper = resultWrapper; }
public void Constructor_Throws_WhenContentNegotiatorIsNull() { // Arrange string routeName = CreateRouteName(); IDictionary <string, object> routeValues = CreateRouteValues(); object content = CreateContent(); UrlHelper urlFactory = CreateDummyUrlFactory(); IContentNegotiator contentNegotiator = null; using (HttpRequestMessage request = CreateRequest()) { IEnumerable <MediaTypeFormatter> formatters = CreateFormatters(); // Act & Assert Assert.ThrowsArgumentNull(() => { CreateProductUnderTest(routeName, routeValues, content, urlFactory, contentNegotiator, request, formatters); }, "contentNegotiator"); } }
public void Location_Returns_InstanceProvided() { // Arrange Uri expectedLocation = CreateLocation(); object content = CreateContent(); IContentNegotiator contentNegotiator = CreateDummyContentNegotiator(); using (HttpRequestMessage request = CreateRequest()) { IEnumerable <MediaTypeFormatter> formatters = CreateFormatters(); CreatedNegotiatedContentResult <object> result = CreateProductUnderTest(expectedLocation, content, contentNegotiator, request, formatters); // Act Uri location = result.Location; // Assert Assert.Same(expectedLocation, location); } }
public void ContentNegotiator_ForApiController_EvaluatesLazily() { // Arrange HttpStatusCode statusCode = CreateStatusCode(); object content = CreateContent(); ApiController controller = CreateController(); using ( HttpConfiguration configuration = CreateConfiguration( CreateFormatter(), CreateContentNegotiator() ) ) { controller.Configuration = configuration; using (HttpRequestMessage request = CreateRequest()) { controller.Request = request; NegotiatedContentResult <object> result = new NegotiatedContentResult <object>( statusCode, content, controller ); IContentNegotiator expectedContentNegotiator = CreateContentNegotiator(); configuration.Services.Replace( typeof(IContentNegotiator), expectedContentNegotiator ); // Act IContentNegotiator contentNegotiator = result.ContentNegotiator; // Assert Assert.Same(expectedContentNegotiator, contentNegotiator); } } }
private void EnsureResolved() { if (_resolvedDependencies == null) { HttpRequestContext requestContext = _controller.RequestContext; Contract.Assert(requestContext != null); bool includeErrorDetail = requestContext.IncludeErrorDetail; HttpConfiguration configuration = _controller.Configuration; if (configuration == null) { throw new InvalidOperationException( SRResources.HttpControllerContext_ConfigurationMustNotBeNull); } ServicesContainer services = configuration.Services; Contract.Assert(services != null); IContentNegotiator contentNegotiator = services.GetContentNegotiator(); if (contentNegotiator == null) { throw new InvalidOperationException(Error.Format( SRResources.HttpRequestMessageExtensions_NoContentNegotiator, typeof(IContentNegotiator))); } HttpRequestMessage request = _controller.Request; if (request == null) { throw new InvalidOperationException(SRResources.ApiController_RequestMustNotBeNull); } IEnumerable <MediaTypeFormatter> formatters = configuration.Formatters; Contract.Assert(formatters != null); _resolvedDependencies = new DirectDependencyProvider(includeErrorDetail, contentNegotiator, request, formatters); } }
/// <summary> /// Helper method that performs content negotiation and creates a <see cref="HttpResponseMessage"/> with an instance /// of <see cref="ObjectContent{T}"/> as the content if a formatter can be found. If no formatter is found, this /// method returns a response with status 406 NotAcceptable. /// </summary> /// <remarks> /// This method will use the provided <paramref name="configuration"/> or it will get the /// <see cref="HttpConfiguration"/> instance associated with <paramref name="request"/>. /// </remarks> /// <typeparam name="T">The type of the value.</typeparam> /// <param name="request">The request.</param> /// <param name="statusCode">The status code of the created response.</param> /// <param name="value">The value to wrap. Can be <c>null</c>.</param> /// <param name="configuration">The configuration to use. Can be <c>null</c>.</param> /// <returns>A response wrapping <paramref name="value"/> with <paramref name="statusCode"/>.</returns> public static HttpResponseMessage CreateResponse <T>( this HttpRequestMessage request, HttpStatusCode statusCode, T value, HttpConfiguration configuration ) { if (request == null) { throw Error.ArgumentNull("request"); } configuration = configuration ?? request.GetConfiguration(); if (configuration == null) { throw Error.InvalidOperation( SRResources.HttpRequestMessageExtensions_NoConfiguration ); } IContentNegotiator contentNegotiator = configuration.Services.GetContentNegotiator(); if (contentNegotiator == null) { throw Error.InvalidOperation( SRResources.HttpRequestMessageExtensions_NoContentNegotiator, typeof(IContentNegotiator).FullName ); } IEnumerable <MediaTypeFormatter> formatters = configuration.Formatters; return(NegotiatedContentResult <T> .Execute( statusCode, value, contentNegotiator, request, formatters )); }
public void ContentNegotiator_ForApiController_EvaluatesLazily() { // Arrange Uri location = CreateLocation(); object content = CreateContent(); ApiController controller = CreateController(); using ( HttpConfiguration configuration = CreateConfiguration( CreateFormatter(), CreateDummyContentNegotiator() ) ) { controller.Configuration = configuration; using (HttpRequestMessage request = CreateRequest()) { controller.Request = request; CreatedNegotiatedContentResult <object> result = CreateProductUnderTest( location, content, controller ); IContentNegotiator expectedContentNegotiator = CreateDummyContentNegotiator(); configuration.Services.Replace( typeof(IContentNegotiator), expectedContentNegotiator ); // Act IContentNegotiator contentNegotiator = result.ContentNegotiator; // Assert Assert.Same(expectedContentNegotiator, contentNegotiator); } } }
/// <summary> /// Callback invoked to set per-controller overrides for this controllerDescriptor. /// </summary> /// <param name="controllerSettings">The controller settings to initialize.</param> /// <param name="controllerDescriptor">The controller descriptor. Note that the <see /// cref="T:System.Web.Http.Controllers.HttpControllerDescriptor" /> can be associated with the derived /// controller type given that <see cref="T:System.Web.Http.Controllers.IControllerConfiguration" /> is /// inherited.</param> public void Initialize(HttpControllerSettings controllerSettings, HttpControllerDescriptor controllerDescriptor) { if (controllerSettings == null) { throw Error.ArgumentNull("controllerSettings"); } if (controllerDescriptor == null) { throw Error.ArgumentNull("controllerDescriptor"); } // If any OData formatters are registered globally, do nothing and use those instead MediaTypeFormatterCollection controllerFormatters = controllerSettings.Formatters; if (!controllerFormatters.Where(f => f != null && Decorator.GetInner(f) is ODataMediaTypeFormatter).Any()) { // Remove Xml and Json formatters to avoid media type conflicts controllerFormatters.RemoveRange( controllerFormatters.Where(f => f is XmlMediaTypeFormatter || f is JsonMediaTypeFormatter)); controllerFormatters.InsertRange(0, CreateODataFormatters()); } ServicesContainer services = controllerSettings.Services; Contract.Assert(services != null); // Replace the action value binder with one that attaches the request to the formatter. IActionValueBinder originalActionValueBinder = services.GetActionValueBinder(); IActionValueBinder actionValueBinder = new PerRequestActionValueBinder(originalActionValueBinder); controllerSettings.Services.Replace(typeof(IActionValueBinder), actionValueBinder); // Replace the content negotiator with one that uses the per-request formatters. // This negotiator is required to allow CanReadType to have access to the model. IContentNegotiator originalContentNegotiator = services.GetContentNegotiator(); IContentNegotiator contentNegotiator = new PerRequestContentNegotiator(originalContentNegotiator); controllerSettings.Services.Replace(typeof(IContentNegotiator), contentNegotiator); }
public DirectDependencyProvider(bool includeErrorDetail, IContentNegotiator contentNegotiator, HttpRequestMessage request, IEnumerable<MediaTypeFormatter> formatters) { if (contentNegotiator == null) { throw new ArgumentNullException("contentNegotiator"); } if (request == null) { throw new ArgumentNullException("request"); } if (formatters == null) { throw new ArgumentNullException("formatters"); } _includeErrorDetail = includeErrorDetail; _contentNegotiator = contentNegotiator; _request = request; _formatters = formatters; }
public async Task 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); using (HttpResponseMessage response = await task) { Assert.NotNull(response); Assert.Equal(HttpStatusCode.NotAcceptable, response.StatusCode); Assert.Null(response.Headers.Location); Assert.Same(expectedRequest, response.RequestMessage); } } }
internal static HttpResponseMessage Execute(HttpStatusCode statusCode, T content, IContentNegotiator contentNegotiator, HttpRequestMessage request, IEnumerable <MediaTypeFormatter> formatters) { Contract.Assert(contentNegotiator != null); Contract.Assert(request != null); Contract.Assert(formatters != null); // Run content negotiation. ContentNegotiationResult result = contentNegotiator.Negotiate(typeof(T), request, 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 = statusCode; 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 = request; } catch { response.Dispose(); throw; } return(response); }
public DirectDependencyProvider(bool includeErrorDetail, IContentNegotiator contentNegotiator, HttpRequestMessage request, IEnumerable <MediaTypeFormatter> formatters) { if (contentNegotiator == null) { throw new ArgumentNullException("contentNegotiator"); } if (request == null) { throw new ArgumentNullException("request"); } if (formatters == null) { throw new ArgumentNullException("formatters"); } _includeErrorDetail = includeErrorDetail; _contentNegotiator = contentNegotiator; _request = request; _formatters = formatters; }
public void ContentNegotiator_ForApiController_EvaluatesLazily() { // Arrange string message = CreateMessage(); ApiController controller = CreateController(); using ( HttpConfiguration configuration = CreateConfiguration( CreateFormatter(), CreateDummyContentNegotiator() ) ) { controller.Configuration = configuration; using (HttpRequestMessage request = CreateRequest()) { controller.Request = request; BadRequestErrorMessageResult result = CreateProductUnderTest( message, controller ); IContentNegotiator expectedContentNegotiator = CreateDummyContentNegotiator(); configuration.Services.Replace( typeof(IContentNegotiator), expectedContentNegotiator ); // Act IContentNegotiator contentNegotiator = result.ContentNegotiator; // Assert Assert.Same(expectedContentNegotiator, contentNegotiator); } } }
public HttpResponseMessage GetAutoCompleteData(string searchTerm) { string factualJsonData; try { factualJsonData = repository.GetHealthCareProviderAutocomplete(searchTerm); } catch (FactualApiException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message) }); } // Get the IContentNegotiator IContentNegotiator negotiator = Configuration.Services.GetContentNegotiator(); // Run content negotiation to select a formatter ContentNegotiationResult result = negotiator.Negotiate( typeof(string), this.Request, this.Configuration.Formatters); var response = new HttpResponseMessage(HttpStatusCode.OK); if (result.MediaType.MediaType.Equals("application/xml")) { string json = string.Format("{0}{1}{2}", "{Root: ", factualJsonData, "}"); var doc = (XDocument)JsonConvert.DeserializeXNode(json); response.Content = new StringContent(doc.ToString(), Encoding.UTF8, result.MediaType.MediaType); } else { response.Content = new StringContent(factualJsonData, Encoding.UTF8, "application/json"); } return(response); }
public Task <HttpResponseMessage> InvokeActionAsync(HttpActionContext actionContext, CancellationToken cancellationToken) { ReflectedHttpActionDescriptor actionDescriptor = (ReflectedHttpActionDescriptor)actionContext.ActionDescriptor; //提取参数数组 List <object> arguments = new List <object>(); ParameterInfo[] parameters = actionDescriptor.MethodInfo.GetParameters(); for (int i = 0; i < parameters.Length; i++) { string parameterName = parameters[i].Name; arguments.Add(actionContext.ActionArguments[parameterName]); } //利用ActionExecutor执行目标Action方法 Task <object> task = new ActionExecutor(actionDescriptor.MethodInfo).Execute(actionContext.ControllerContext.Controller, arguments.ToArray()); //创建HttpResponseMessage object result = task.Result; HttpResponseMessage response = result as HttpResponseMessage; if (null == response) { //利用"媒体类型协商机制"创建MediaTypeFormatter IContentNegotiator negotiator = actionContext.ControllerContext.Configuration.Services.GetContentNegotiator(); MediaTypeFormatter formatter = negotiator.Negotiate(result.GetType(), actionContext.Request, actionContext.ControllerContext.Configuration.Formatters).Formatter; response = new HttpResponseMessage(HttpStatusCode.OK) { Content = new ObjectContent(result.GetType(), result, formatter) }; } //创建并返回Task<HttpResponseMessage> TaskCompletionSource <HttpResponseMessage> completionSource = new TaskCompletionSource <HttpResponseMessage>(); completionSource.SetResult(response); return(completionSource.Task); }
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 contentNegotiationResult = contentNegotiator.Negotiate(typeof(object), Request, Configuration.Formatters); if (contentNegotiationResult == null) { throw new HttpResponseException(HttpStatusCode.NotAcceptable); } return(Request.CreateResponse(HttpStatusCode.OK, new ResultMessage { Message = "Hello" }, contentNegotiationResult.Formatter, contentNegotiationResult.MediaType)); #endregion }
public void ContentNegotiator_ForApiController_Throws_WhenConfigurationIsNull() { // Arrange ModelStateDictionary modelState = CreateModelState(); ApiController controller = CreateController(); HttpControllerContext context = new HttpControllerContext(); using (HttpRequestMessage request = CreateRequest()) { controller.ControllerContext = context; InvalidModelStateResult result = CreateProductUnderTest(modelState, controller); // Act & Assert Assert.Throws <InvalidOperationException>( () => { IContentNegotiator ignore = result.ContentNegotiator; }, "HttpControllerContext.Configuration must not be null." ); } }
public void Formatters_Returns_InstanceProvided() { // Arrange string routeName = CreateRouteName(); IDictionary <string, object> routeValues = CreateRouteValues(); object content = CreateContent(); UrlHelper urlFactory = CreateDummyUrlFactory(); IContentNegotiator contentNegotiator = CreateDummyContentNegotiator(); using (HttpRequestMessage request = CreateRequest()) { IEnumerable <MediaTypeFormatter> expectedFormatters = CreateFormatters(); CreatedAtRouteNegotiatedContentResult <object> result = CreateProductUnderTest(routeName, routeValues, content, urlFactory, contentNegotiator, request, expectedFormatters); // Act IEnumerable <MediaTypeFormatter> formatters = result.Formatters; // Assert Assert.Same(expectedFormatters, formatters); } }
public void ContentNegotiator_ForApiController_Throws_WhenConfigurationIsNull() { // Arrange string routeName = CreateRouteName(); IDictionary <string, object> routeValues = CreateRouteValues(); object content = CreateContent(); ApiController controller = CreateController(); HttpControllerContext context = new HttpControllerContext(); using (HttpRequestMessage request = CreateRequest()) { controller.ControllerContext = context; controller.Request = request; CreatedAtRouteNegotiatedContentResult <object> result = CreateProductUnderTest(routeName, routeValues, content, controller); // Act & Assert Assert.Throws <InvalidOperationException>( () => { IContentNegotiator ignore = result.ContentNegotiator; }, "HttpControllerContext.Configuration must not be null."); } }
public void ExecuteAsync_Returns_CorrectResponse_WhenContentNegotiationFails() { // Arrange string routeName = CreateRouteName(); IDictionary <string, object> routeValues = CreateRouteValues(); object content = CreateContent(); UrlHelper urlFactory = CreateDummyUrlFactory(); 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(routeName, routeValues, content, urlFactory, 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); } } }
private void EnsureResolved() { if (_resolvedDependencies == null) { HttpRequestContext requestContext = _controller.RequestContext; Contract.Assert(requestContext != null); bool includeErrorDetail = requestContext.IncludeErrorDetail; HttpConfiguration configuration = _controller.Configuration; if (configuration == null) { throw new InvalidOperationException("Configuration must not be null."); } ServicesContainer services = configuration.Services; Contract.Assert(services != null); IContentNegotiator contentNegotiator = services.GetContentNegotiator(); if (contentNegotiator == null) { throw new InvalidOperationException("ContentNegotiator must not be null."); } HttpRequestMessage request = _controller.Request; if (request == null) { throw new InvalidOperationException("Request must not be null."); } IEnumerable <MediaTypeFormatter> formatters = configuration.Formatters; Contract.Assert(formatters != null); _resolvedDependencies = new DirectDependencyProvider(includeErrorDetail, contentNegotiator, request, formatters); } }
private static CreatedAtRouteNegotiatedContentResult<object> CreateProductUnderTest(string routeName, IDictionary<string, object> routeValues, object content, UrlHelper urlFactory, IContentNegotiator contentNegotiator, HttpRequestMessage request, IEnumerable<MediaTypeFormatter> formatters) { return new CreatedAtRouteNegotiatedContentResult<object>(routeName, routeValues, content, urlFactory, contentNegotiator, request, formatters); }
public void Initialize() { m_contentNegotiator = Rest.Configuration.ServiceLocator.GetService<IContentNegotiator>(); }
public ContentNegotiatorTracer(IContentNegotiator innerNegotiator, ITraceWriter traceWriter) { _innerNegotiator = innerNegotiator; _traceWriter = traceWriter; }
private static IServiceProvider CreateServices( IContentNegotiator contentNegotiator = null, MediaTypeFormatter formatter = null) { var options = new WebApiCompatShimOptions(); if (formatter == null) { options.Formatters.AddRange(new MediaTypeFormatterCollection()); } else { options.Formatters.Add(formatter); } var optionsAccessor = new Mock<IOptions<WebApiCompatShimOptions>>(); optionsAccessor.SetupGet(o => o.Options).Returns(options); var services = new Mock<IServiceProvider>(MockBehavior.Strict); services .Setup(s => s.GetService(typeof(IOptions<WebApiCompatShimOptions>))) .Returns(optionsAccessor.Object); if (contentNegotiator != null) { services .Setup(s => s.GetService(typeof(IContentNegotiator))) .Returns(contentNegotiator); } return services.Object; }
private static CreatedNegotiatedContentResult<object> CreateProductUnderTest(Uri location, object content, IContentNegotiator contentNegotiator, HttpRequestMessage request, IEnumerable<MediaTypeFormatter> formatters) { return new CreatedNegotiatedContentResult<object>(location, content, contentNegotiator, request, formatters); }
private static HttpConfiguration CreateConfiguration(MediaTypeFormatter formatter, IContentNegotiator contentNegotiator) { HttpConfiguration configuration = new HttpConfiguration(); configuration.Formatters.Clear(); configuration.Formatters.Add(formatter); configuration.Services.Replace(typeof(IContentNegotiator), contentNegotiator); return configuration; }
/// <summary>Initializes a new instance of the <see cref="BadRequestErrorMessageResult"/> class.</summary> /// <param name="message">The user-visible error message.</param> /// <param name="contentNegotiator">The content negotiator to handle content negotiation.</param> /// <param name="request">The request message which led to this result.</param> /// <param name="formatters">The formatters to use to negotiate and format the content.</param> public BadRequestErrorMessageResult(string message, IContentNegotiator contentNegotiator, HttpRequestMessage request, IEnumerable<MediaTypeFormatter> formatters) : this(message, new NegotiatedContentResult<HttpError>.DirectDependencyProvider(contentNegotiator, request, formatters)) { }
private static ExceptionResult CreateProductUnderTest(Exception exception, bool includeErrorDetail, IContentNegotiator contentNegotiator, HttpRequestMessage request, IEnumerable<MediaTypeFormatter> formatters) { return new ExceptionResult(exception, includeErrorDetail, contentNegotiator, request, formatters); }
private static InvalidModelStateResult CreateProductUnderTest(ModelStateDictionary modelState, bool includeErrorDetail, IContentNegotiator contentNegotiator, HttpRequestMessage request, IEnumerable<MediaTypeFormatter> formatters) { return new InvalidModelStateResult(modelState, includeErrorDetail, contentNegotiator, request, formatters); }
private static BadRequestErrorMessageResult CreateProductUnderTest(string message, IContentNegotiator contentNegotiator, HttpRequestMessage request, IEnumerable<MediaTypeFormatter> formatters) { return new BadRequestErrorMessageResult(message, contentNegotiator, request, formatters); }