Esempio n. 1
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
                    )
            });
        }
        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
                });
            }
        }
        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.
        }
Esempio n. 4
0
        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
                    )
            });
        }
Esempio n. 5
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
            });
        }
Esempio n. 6
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
                    )
            });
        }
        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)
            };
        }
Esempio n. 8
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
        }
Esempio n. 9
0
        internal static ContentNegotiationResult Negotiate(this HttpRequestMessage request)
        {
            HttpConfiguration  configuration            = request.GetConfiguration();
            IContentNegotiator contentNegotiator        = configuration.Services.GetContentNegotiator();
            IEnumerable <MediaTypeFormatter> formatters = configuration.Formatters;

            return(contentNegotiator.Negotiate(typeof(StoredProcedureResponse), request, formatters));
        }
Esempio n. 10
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);
        }
        public static HttpContent GetContent(HttpRequestMessage request)
        {
            var requestMsg = (request.Properties[HeaderName] as List <FilterModel>);
            HttpConfiguration  configuration = request.GetConfiguration();
            IContentNegotiator negotiator    = configuration.Services.GetContentNegotiator();
            var negotiatorResult             = negotiator.Negotiate(typeof(List <FilterModel>), request, configuration.Formatters);

            return(new ObjectContent <List <FilterModel> >(requestMsg, negotiatorResult.Formatter));
        }
Esempio n. 12
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));
        }
Esempio n. 13
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);
            }
        }
Esempio n. 14
0
        protected override Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            var mediaType = contentNegotiator.Negotiate(formatters.Keys, request.Headers.Accept);
            var tcs       = new TaskCompletionSource <HttpResponseMessage>();

            tcs.SetResult(new HttpResponseMessage
            {
                Content = ApplyTemplate("value", mediaType),
            });
            return(tcs.Task);
        }
Esempio n. 15
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));
        }
Esempio n. 16
0
        public static HttpResponseMessage ReturnContent(object returnObj, IContentNegotiator content, MediaTypeFormatterCollection formatter, HttpRequestMessage request)
        {
            IContentNegotiator       negotiator = content;
            ContentNegotiationResult result     = null;

            result = negotiator.Negotiate(typeof(object), request, formatter);
            return(new HttpResponseMessage()
            {
                StatusCode = HttpStatusCode.OK,
                Content = new ObjectContent <object>(returnObj, result.Formatter, result.MediaType.MediaType)
            });
        }
Esempio n. 17
0
        public static ContentNegotiationResult Negotiate(this IContentNegotiator contentNegotiator, IEnumerable <MediaTypeFormatter> formatters, IEnumerable <MediaTypeWithQualityHeaderValue> accept)
        {
            using (var request = new HttpRequestMessage())
            {
                foreach (var header in accept)
                {
                    request.Headers.Accept.Add(header);
                }

                return(contentNegotiator.Negotiate(typeof(object), request, formatters));
            }
        }
        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);
        }
Esempio n. 19
0
        public IEnumerable <string> Get()
        {
            HttpRequestMessage request1 = this.CreateRequestMessage(null, "application/json", "utf-7;q=0.4, utf-8;q=0.8, utf-16;q=1.0");
            HttpRequestMessage request2 = this.CreateRequestMessage(null, "application/json", "utf-7, utf-8, utf-16");
            HttpRequestMessage request3 = this.CreateRequestMessage("utf-8", "application/json", null);
            HttpRequestMessage request4 = this.CreateRequestMessage(null, "application/json", null);

            HttpRequestMessage[] requests   = new HttpRequestMessage[] { request1, request2, request3, request4 };
            IContentNegotiator   negotiator = this.Configuration.Services.GetContentNegotiator();

            MediaTypeFormatter[] formatters = new MediaTypeFormatter[] { new JsonFormatter() };
            return(from request in requests
                   select negotiator.Negotiate(typeof(string), request, formatters).MediaType.CharSet);
        }
Esempio n. 20
0
        public ContentNegotiationResult Negotiate(Type type, HttpRequestMessage request, IEnumerable <MediaTypeFormatter> formatters)
        {
            MediaTypeHeaderValue mediaType = request.Content == null ? null : request.Content.Headers.ContentType;

            List <MediaTypeFormatter> perRequestFormatters = new List <MediaTypeFormatter>();

            foreach (MediaTypeFormatter formatter in formatters)
            {
                if (formatter != null)
                {
                    perRequestFormatters.Add(formatter.GetPerRequestFormatterInstance(type, request, mediaType));
                }
            }
            return(_innerContentNegotiator.Negotiate(type, request, perRequestFormatters));
        }
Esempio n. 21
0
        public static string Negotiate(this IContentNegotiator contentNegotiator, IEnumerable <string> supportedMediaTypes, IEnumerable <MediaTypeWithQualityHeaderValue> accept)
        {
            var formatters = supportedMediaTypes.Select(mt => new ConnegFormatter(mt));

            using (var request = new HttpRequestMessage())
            {
                foreach (var header in accept)
                {
                    request.Headers.Accept.Add(header);
                }

                var result = contentNegotiator.Negotiate(typeof(object), request, formatters);
                return(result.MediaType.MediaType);
            }
        }
Esempio n. 22
0
        private static HttpResponseMessage CreateNegotiatedResponse(HttpRequestMessage request, HttpStatusCode statusCode, object content)
        {
            HttpResponseMessage result = request.CreateResponse(statusCode);

            if (content == null)
            {
                return(result);
            }

            var configuration             = request.GetConfiguration();
            IContentNegotiator negotiator = configuration.Services.GetContentNegotiator();
            var negotiationResult         = negotiator.Negotiate(content.GetType(), request, configuration.Formatters);

            result.Content = new ObjectContent(content.GetType(), content, negotiationResult.Formatter, negotiationResult.MediaType);

            return(result);
        }
        public IEnumerable <string> Get()
        {
            HttpRequestMessage request1 = this.CreateRequestMessage(null, null, "x-formatted-by", "baz-formatter");
            HttpRequestMessage request2 = this.CreateRequestMessage(null, "application/foo;q=0.4, application/bar;q=0.6, text/baz;q=0.8", null, null);
            HttpRequestMessage request3 = this.CreateRequestMessage(null, "applicaiton/*, text/baz, */*", null, null);
            HttpRequestMessage request4 = this.CreateRequestMessage(null, "text/*, */*", null, null);
            HttpRequestMessage request5 = this.CreateRequestMessage(null, "*/*", null, null);
            HttpRequestMessage request6 = this.CreateRequestMessage("application/json", "image/jpeg", null, null);
            HttpRequestMessage request7 = this.CreateRequestMessage(null, null, null, null);

            HttpRequestMessage[] requests   = new HttpRequestMessage[] { request1, request2, request3, request4, request5, request6, request7 };
            IContentNegotiator   negotiator = this.Configuration.Services.GetContentNegotiator();

            MediaTypeFormatter[] formatters = new MediaTypeFormatter[] { new FooFormatter(), new BarFormatter(), new BazFormatter(), new JsonMediaTypeFormatter() };
            return(from request in requests
                   select negotiator.Negotiate(typeof(string), request, formatters).Formatter.GetType().Name);
        }
Esempio n. 24
0
        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;

            // Run content negotiation
            ContentNegotiationResult result = contentNegotiator.Negotiate(typeof(T), 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 <T>(value, result.Formatter, mediaType),
                    StatusCode = statusCode,
                    RequestMessage = request
                });
            }
        }
Esempio n. 25
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);
        }
        // PUT api/product/5
        public HttpResponseMessage Put(ProductListViewModel.ProductListItemViewModel value)
        {
            Mapper.CreateMap <ProductListViewModel.ProductListItemViewModel, Product>();
            Mapper.CreateMap <ProductListViewModel.ProductListItemViewModel.ProductVariantListItemViewModel, Product.ProductVariant>();
            var item    = _ProductService.GetProductById(value.Id);
            var product = Mapper.Map(value, item);

            _ProductService.SaveProduct(item);
            DataManager.SaveChanges();
            var result = new HttpResponseMessage(HttpStatusCode.OK);
            IContentNegotiator   negotiator = Configuration.Services.GetContentNegotiator();
            MediaTypeHeaderValue mediaType;
            var contentNegotiationResult = negotiator.Negotiate(typeof(ProductListViewModel.ProductListItemViewModel), Request, Configuration.Formatters);

            result.Content = new System.Net.Http.ObjectContent <ProductListViewModel.ProductListItemViewModel>(value, contentNegotiationResult.Formatter);

            return(result);
        }
Esempio n. 27
0
        private static HttpResponseMessage CreateResponse(object data, Type dataType, HttpStatusCode code,
                                                          HttpRequestMessage request)
        {
            var configuration = request.GetConfiguration();

            IContentNegotiator       negotiator = configuration.Services.GetContentNegotiator();
            ContentNegotiationResult result     = negotiator.Negotiate(dataType, request, configuration.Formatters);

            var bestMatchFormatter = result.Formatter;
            var mediaType          = result.MediaType.MediaType;

            return(new HttpResponseMessage
            {
                Content = new ObjectContent(dataType, data, bestMatchFormatter, mediaType),
                StatusCode = code,
                RequestMessage = request
            });
        }
        internal virtual ISerializer Create(String contentType)
        {
            if (contentType == null)
            {
                throw new ArgumentNullException(nameof(contentType));
            }

            var result = _negotiator.Negotiate(contentType);

            foreach (var header in result)
            {
                foreach (var serializer in _serializers)
                {
                    if (serializer.Key(header))
                    {
                        return(serializer.Value);
                    }
                }
            }

            return(NullSerializer.Instance);
        }
        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 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);
        }