示例#1
0
 protected override sealed double OnTryMatchMediaType(HttpRequestMessage request)
 {
     if (!string.Equals(GetUriPathExtensionOrNull(request.RequestUri), this.UriPathExtension, StringComparison.Ordinal))
     {
         return 0.0;
     }
     return 1.0;
 }
示例#2
0
 public double TryMatchMediaType(HttpRequestMessage request)
 {
     if (request == null)
     {
         throw new ArgumentNullException("request");
     }
     return this.OnTryMatchMediaType(request);
 }
示例#3
0
 protected override double OnTryMatchMediaType(HttpRequestMessage request)
 {
     if (request == null)
     {
         throw new ArgumentNullException("request");
     }
     return MatchHeaderValue(request, this.HeaderName, this.HeaderValue, this.HeaderValueComparison, this.IsValueSubstring);
 }
示例#4
0
 protected override sealed double OnTryMatchMediaType(HttpRequestMessage request)
 {
     NameValueCollection queryString = request.QueryString;
     if (!this.DoesQueryStringMatch(queryString))
     {
         return 0.0;
     }
     return 1.0;
 }
示例#5
0
        public override void WriteToStream(Type type, object value, Stream stream, HttpRequestMessage requestMessage)
        {
            if (TryGetDelegatingTypeForIQueryableGenericOrSame(ref type) ||
                TryGetDelegatingTypeForIEnumerableGenericOrSame(ref type))
            {
                value = GetTypeRemappingConstructor(type).Invoke(new object[] { value });
            }

            new XmlSerializer(type).Serialize(stream, value);
            //new DataContractSerializer(type).WriteObject(stream, value);
        }
示例#6
0
 protected override double OnTryMatchMediaType(HttpRequestMessage request)
 {
     if (request == null)
     {
         throw new ArgumentNullException("request");
     }
     var acceptHeaders = request.AcceptHeaders;
     if (acceptHeaders != null && acceptHeaders.Count() != 1 || !acceptHeaders.First<MediaTypeWithQualityHeaderValue>().MediaType.Equals("*/*", StringComparison.Ordinal))
     {
         return 0.0;
     }
     return base.OnTryMatchMediaType(request);
 }
示例#7
0
 internal static HttpRequestMessage ConvertRequest(HttpContextBase httpContextBase)
 {
     HttpRequestBase request = httpContextBase.Request;
     //HttpMethod httpMethod = HttpMethod.GetHttpMethod(request.HttpMethod);
     Uri url = request.Url;
     //HttpRequestMessage httpRequestMessage = new HttpRequestMessage(httpMethod, url);
     HttpRequestMessage httpRequestMessage = new HttpRequestMessage(request.HttpMethod, url);
     foreach (string header in request.Headers)
     {
         string[] headers = request.Headers.GetValues(header);
         httpRequestMessage.Headers.Add(header, headers);
     }
     httpRequestMessage.HttpContext = httpContextBase;
     return httpRequestMessage;
 }
示例#8
0
        /// <summary>
        /// Performs content negotiating by selecting the most appropriate <see cref="MediaTypeFormatter"/> out of the passed in
        /// <paramref name="formatters"/> for the given <paramref name="request"/> that can serialize an object of the given
        /// <paramref name="type"/>.
        /// </summary>
        /// <param name="type">The type to be serialized.</param>
        /// <param name="request">The request.</param>
        /// <param name="formatters">The set of <see cref="MediaTypeFormatter"/> objects from which to choose.</param>
        /// <returns>The result of the negotiation containing the most appropriate <see cref="MediaTypeFormatter"/> instance,
        /// or <c>null</c> if there is no appropriate formatter.</returns>
        public virtual ContentNegotiationResult Negotiate(Type type, HttpRequestMessage request, IEnumerable<MediaTypeFormatter> formatters)
        {
            if (type == null)
            {
                throw Error.ArgumentNull("type");
            }
            if (request == null)
            {
                throw Error.ArgumentNull("request");
            }
            if (formatters == null)
            {
                throw Error.ArgumentNull("formatters");
            }

            // If formatter list is empty then we won't find a match
            if (!formatters.Any())
            {
                return null;
            }

            // Go through each formatter to compute how well it matches.
            Collection<MediaTypeFormatterMatch> matches = ComputeFormatterMatches(type, request, formatters);

            // Select best formatter match among the matches
            MediaTypeFormatterMatch bestFormatterMatch = SelectResponseMediaTypeFormatter(matches);

            // We found a best formatter
            if (bestFormatterMatch != null)
            {
                // Find the best character encoding for the selected formatter
                //Encoding bestEncodingMatch = SelectResponseCharacterEncoding(request, bestFormatterMatch.Formatter);
                Encoding bestEncodingMatch = bestFormatterMatch.Formatter.SelectCharacterEncoding(request);
                if (bestEncodingMatch != null)
                {
                    bestFormatterMatch.MediaType.CharSet = bestEncodingMatch.WebName;
                }

                MediaTypeHeaderValue bestMediaType = bestFormatterMatch.MediaType;
                MediaTypeFormatter bestFormatter = bestFormatterMatch.Formatter.GetPerRequestFormatterInstance(type, request, bestMediaType);
                return new ContentNegotiationResult(bestFormatter, bestMediaType);
            }

            return null;
        }
示例#9
0
 private static double MatchHeaderValue(HttpRequestMessage request, string headerName, string headerValue, StringComparison valueComparison, bool isValueSubstring)
 {
     IEnumerable<string> headerValues = request.Headers[headerName];
     if (headerValues != null)
     {
         foreach (string header in headerValues)
         {
             if (isValueSubstring)
             {
                 if (header.IndexOf(headerValue, valueComparison) != -1)
                 {
                     return 1.0;
                 }
             }
             else if (header.Equals(headerValue, valueComparison))
             {
                 return 1.0;
             }
         }
     }
     return 0.0;
 }
示例#10
0
        public override void WriteToStream(Type type, object value, Stream stream, HttpRequestMessage requestMessage)
        {
            Encoding effectiveEncoding = this.SelectCharacterEncoding(requestMessage);

            if (TryGetDelegatingTypeForIQueryableGenericOrSame(ref type))
            {
                value = GetTypeRemappingConstructor(type).Invoke(new object[] { value });
            }
            using (JsonTextWriter jsonTextWriter = new JsonTextWriter(new StreamWriter(stream, effectiveEncoding)) { CloseOutput = false })
            {
                if (Indent)
                {
                    jsonTextWriter.Formatting = Formatting.Indented;
                }
                var serializer = JsonSerializer.Create(this.serializerSettings);
                serializer.Serialize(jsonTextWriter, value);
                jsonTextWriter.Flush();
            }
            // TODO: Consider enabling DataContractSerializer
            //if (!UseDataContractSerializer)
            //{
            //}
            //else
            //{
            //    DataContractJsonSerializer dataContractSerializer = this.GetDataContractSerializer(type);
            //    bool ownsStream = false;
            //    using (XmlWriter writer = JsonReaderWriterFactory.CreateJsonWriter(stream, effectiveEncoding, ownsStream))
            //    {
            //        dataContractSerializer.WriteObject(writer, value);
            //    }
            //}
        }
示例#11
0
        /// <summary>
        /// Determine the best character encoding for writing the response. First we look
        /// for accept-charset headers and if not found then we try to match
        /// any charset encoding in the request (in case of PUT, POST, etc.)
        /// If no encoding is found then we use the default for the formatter.
        /// </summary>
        /// <returns>The <see cref="Encoding"/> determined to be the best match.</returns>
        protected virtual Encoding SelectResponseCharacterEncoding(HttpRequestMessage request, MediaTypeFormatter formatter)
        {
            if (request == null)
            {
                throw Error.ArgumentNull("request");
            }
            if (formatter == null)
            {
                throw Error.ArgumentNull("formatter");
            }

            // If there are any SupportedEncodings then we pick an encoding
            if (formatter.SupportedEncodings.Count > 0)
            {
                // Sort Accept-Charset header values
                //IEnumerable<StringWithQualityHeaderValue> sortedAcceptCharsetValues = SortStringWithQualityHeaderValuesByQFactor(request.Headers.AcceptCharset);
                // TODO: Fix instead of using Formatter.SelectCharacterEncoding();
                IEnumerable<StringWithQualityHeaderValue> sortedAcceptCharsetValues = Enumerable.Empty<StringWithQualityHeaderValue>();

                // Check for match based on accept-charset headers
                foreach (StringWithQualityHeaderValue acceptCharset in sortedAcceptCharsetValues)
                {
                    foreach (Encoding encoding in formatter.SupportedEncodings)
                    {
                        if (encoding != null && acceptCharset.Quality != FormattingUtilities.NoMatch &&
                            (acceptCharset.Value.Equals(encoding.WebName, StringComparison.OrdinalIgnoreCase) ||
                            acceptCharset.Value.Equals("*", StringComparison.OrdinalIgnoreCase)))
                        {
                            return encoding;
                        }
                    }
                }

                // Check for match based on any request entity body
                return formatter.SelectCharacterEncoding(request);
            }

            return null;
        }
示例#12
0
 internal static HttpResponseMessage ConvertResponse(HttpContextBase httpContextBase, HttpRequestMessage request)
 {
     return null;
 }
示例#13
0
        /// <summary>
        /// Determines the best <see cref="Encoding"/> amongst the supported encodings
        /// for reading or writing an HTTP entity body based on the provided <paramref name="contentHeaders"/>.
        /// </summary>
        /// <param name="contentHeaders">The content headers provided as part of the request or response.</param>
        /// <returns>The <see cref="Encoding"/> to use when reading the request or writing the response.</returns>
        public Encoding SelectCharacterEncoding(HttpRequestMessage contentHeaders)
        {
            Encoding encoding = null;
            if (contentHeaders != null && contentHeaders.ContentType != null)
            {
                // Find encoding based on content type charset parameter
                string charset = contentHeaders.ContentType.CharSet;
                if (!String.IsNullOrWhiteSpace(charset))
                {
                    encoding =
                        SupportedEncodings.FirstOrDefault(
                            enc => charset.Equals(enc.WebName, StringComparison.OrdinalIgnoreCase));
                }
            }

            if (encoding == null)
            {
                // We didn't find a character encoding match based on the content headers.
                // Instead we try getting the default character encoding.
                encoding = SupportedEncodings.FirstOrDefault();
            }

            if (encoding == null)
            {
                // No supported encoding was found so there is no way for us to start reading or writing.
                throw new InvalidOperationException(string.Format(SRResources.MediaTypeFormatterNoEncoding, GetType().Name));
            }

            return encoding;
        }
示例#14
0
 protected override sealed double OnTryMatchMediaType(HttpRequestMessage request)
 {
     return 0.0;
 }
示例#15
0
 protected abstract double OnTryMatchMediaType(HttpRequestMessage request);
示例#16
0
        /// <summary>
        /// Gets the EDM model for the given type and request.
        /// </summary>
        /// <param name="elementClrType">The CLR type to retrieve a model for.</param>
        /// <param name="request">The request message to retrieve a model for.</param>
        /// <param name="actionDescriptor">The action descriptor for the action being queried on.</param>
        /// <returns>The EDM model for the given type and request.</returns>
        /// <remarks>
        /// Override this method to customize the EDM model used for querying.
        /// </remarks>
        public virtual IEdmModel GetModel(Type elementClrType, HttpRequestMessage request, ApiActionDescriptor actionDescriptor)
        {
            // Get model for the request
            IEdmModel model = request.GetEdmModel();

            if (model == null || model.GetEdmType(elementClrType) == null)
            {
                // user has not configured anything or has registered a model without the element type
                // let's create one just for this type and cache it in the action descriptor
                model = actionDescriptor.GetEdmModel(elementClrType);
            }

            Contract.Assert(model != null);
            return model;
        }
示例#17
0
        public virtual void ValidateQuery(HttpRequestMessage request, ODataQueryOptions queryOptions)
        {
            if (request == null)
            {
                throw new ArgumentNullException("request");
            }

            if (queryOptions == null)
            {
                throw new ArgumentNullException("queryOptions");
            }

            foreach (string key in request.QueryString.Keys)
            {
                if (!ODataQueryOptions.IsSupported(key) && key.StartsWith("$", StringComparison.Ordinal))
                {
                    // we don't support any custom query options that start with $
                    throw new HttpException((int)HttpStatusCode.BadRequest, Error.Format("The query parameter '{0}' is not supported.", key));
                }
            }

            queryOptions.Validate(_validationSettings);
        }
示例#18
0
 public abstract void WriteToStream(Type type, object value, Stream stream, HttpRequestMessage requestMessage);
示例#19
0
        /// <summary>
        /// Determine how well each formatter matches by associating a <see cref="MediaTypeFormatterMatchRanking"/> value
        /// with the formatter. Then associate the quality of the match based on q-factors and other parameters. The result of this 
        /// method is a collection of the matches found categorized and assigned a quality value.
        /// </summary>
        /// <param name="type">The type to be serialized.</param>
        /// <param name="request">The request.</param>
        /// <param name="formatters">The set of <see cref="MediaTypeFormatter"/> objects from which to choose.</param>
        /// <returns>A collection containing all the matches.</returns>
        protected virtual Collection<MediaTypeFormatterMatch> ComputeFormatterMatches(Type type, HttpRequestMessage request, IEnumerable<MediaTypeFormatter> formatters)
        {
            if (type == null)
            {
                throw Error.ArgumentNull("type");
            }
            if (request == null)
            {
                throw Error.ArgumentNull("request");
            }
            if (formatters == null)
            {
                throw Error.ArgumentNull("formatters");
            }

            IEnumerable<MediaTypeWithQualityHeaderValue> sortedAcceptValues = null;

            // Go through each formatter to find how well it matches.
            Collection<MediaTypeFormatterMatch> matches = new Collection<MediaTypeFormatterMatch>();
            foreach (MediaTypeFormatter formatter in formatters)
            {
                MediaTypeFormatterMatch match = null;

                // Check first that formatter can write the actual type
                if (!formatter.CanWriteType(type))
                {
                    // Formatter can't even write the type so no match at all
                    continue;
                }

                // Match against media type mapping.
                if ((match = MatchMediaTypeMapping(request, formatter)) != null)
                {
                    matches.Add(match);
                    continue;
                }

                // Match against the accept header values.
                if (sortedAcceptValues == null)
                {
                    // Sort the Accept header values in descending order based on q-factor
                    sortedAcceptValues = SortMediaTypeWithQualityHeaderValuesByQFactor(request.AcceptHeaders);
                }
                if ((match = MatchAcceptHeader(sortedAcceptValues, formatter)) != null)
                {
                    matches.Add(match);
                    continue;
                }

                // Match against request's media type if any
                if ((match = MatchRequestMediaType(request, formatter)) != null)
                {
                    matches.Add(match);
                    continue;
                }

                // Match against the type of object we are writing out
                if ((match = MatchType(type, formatter)) != null)
                {
                    matches.Add(match);
                    continue;
                }
            }

            return matches;
        }
示例#20
0
        /// <summary>
        /// Returns a specialized instance of the <see cref="MediaTypeFormatter"/> that can handle formatting a response for the given
        /// parameters. This method is called by <see cref="DefaultContentNegotiator"/> after a formatter has been selected through content
        /// negotiation.
        /// </summary>
        /// <remarks>
        /// The default implementation returns <c>this</c> instance. Derived classes can choose to return a new instance if
        /// they need to close over any of the parameters.
        /// </remarks>
        /// <param name="type">The type being serialized.</param>
        /// <param name="request">The request.</param>
        /// <param name="mediaType">The media type chosen for the serialization. Can be <c>null</c>.</param>
        /// <returns>An instance that can format a response to the given <paramref name="request"/>.</returns>
        public virtual MediaTypeFormatter GetPerRequestFormatterInstance(Type type, HttpRequestMessage request, MediaTypeHeaderValue mediaType)
        {
            if (type == null)
            {
                throw Error.ArgumentNull("type");
            }
            if (request == null)
            {
                throw Error.ArgumentNull("request");
            }

            return this;
        }
示例#21
0
        /// <summary>
        /// Match a request against the <see cref="MediaTypeMapping"/>s registered with the formatter.
        /// </summary>
        /// <param name="request">The request to match.</param>
        /// <param name="formatter">The formatter to match against.</param>
        /// <returns>A <see cref="MediaTypeFormatterMatch"/> indicating the quality of the match or null is no match.</returns>
        protected virtual MediaTypeFormatterMatch MatchMediaTypeMapping(HttpRequestMessage request, MediaTypeFormatter formatter)
        {
            if (request == null)
            {
                throw Error.ArgumentNull("request");
            }
            if (formatter == null)
            {
                throw Error.ArgumentNull("formatter");
            }

            foreach (MediaTypeMapping mapping in formatter.MediaTypeMappings)
            {
                double quality;
                if (mapping != null && ((quality = mapping.TryMatchMediaType(request)) > FormattingUtilities.NoMatch))
                {
                    return new MediaTypeFormatterMatch(formatter, mapping.MediaType, quality, MediaTypeFormatterMatchRanking.MatchOnRequestWithMediaTypeMapping);
                }
            }

            return null;
        }
示例#22
0
 internal bool TryMatchMediaTypeMapping(HttpRequestMessage request, out MediaTypeFormatterMatch mediaTypeMatch)
 {
     foreach (MediaTypeMapping mapping in this.MediaTypeMappings)
     {
         double num;
         if ((mapping != null) && ((num = mapping.TryMatchMediaType(request)) > 0.0))
         {
             mediaTypeMatch = new MediaTypeFormatterMatch(mapping.MediaType, num);
             return true;
         }
     }
     mediaTypeMatch = null;
     return false;
 }
示例#23
0
        /// <summary>
        /// Match any request media type (in case there is a request entity body) against the formatter's registered
        /// media types.
        /// </summary>
        /// <param name="request">The request to match.</param>
        /// <param name="formatter">The formatter to match against.</param>
        /// <returns>A <see cref="MediaTypeFormatterMatch"/> indicating the quality of the match or null is no match.</returns>
        protected virtual MediaTypeFormatterMatch MatchRequestMediaType(HttpRequestMessage request, MediaTypeFormatter formatter)
        {
            if (request == null)
            {
                throw Error.ArgumentNull("request");
            }
            if (formatter == null)
            {
                throw Error.ArgumentNull("formatter");
            }

            MediaTypeHeaderValue requestMediaType = request.ContentType;
            if (requestMediaType != null)
            {
                foreach (MediaTypeHeaderValue supportedMediaType in formatter.SupportedMediaTypes)
                {
                    if (supportedMediaType != null && supportedMediaType.IsSubsetOf(requestMediaType))
                    {
                        return new MediaTypeFormatterMatch(formatter, supportedMediaType, FormattingUtilities.Match, MediaTypeFormatterMatchRanking.MatchOnRequestMediaType);
                    }
                }
            }

            return null;
        }