コード例 #1
0
        /// <summary>
        /// Returns a <see cref="Task{T}"/> that will yield a <see cref="NameValueCollection"/> instance containing the form data
        /// parsed as HTML form URL-encoded from the <paramref name="content"/> instance.
        /// </summary>
        /// <param name="content">The content.</param>
        /// <param name="cancellationToken">The token to monitor for cancellation requests.</param>
        /// <returns>A <see cref="Task{T}"/> which will provide the result. If the data can not be read
        /// as HTML form URL-encoded data then the result is null.</returns>
        public static Task<NameValueCollection> ReadAsFormDataAsync(this HttpContent content, CancellationToken cancellationToken)
        {
            if (content == null)
            {
                throw Error.ArgumentNull("content");
            }

            MediaTypeFormatter[] formatters = new MediaTypeFormatter[1] { new FormUrlEncodedMediaTypeFormatter() };
            return ReadAsAsyncCore(content, formatters, cancellationToken);
        }
コード例 #2
0
        /// <summary>
        /// Create the content negotiation result object.
        /// </summary>
        /// <param name="formatter">The formatter.</param>
        /// <param name="mediaType">The preferred media type. Can be <c>null</c>.</param>
        public ContentNegotiationResult(MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType)
        {
            if (formatter == null)
            {
                throw Error.ArgumentNull("formatter");
            }

            this._formatter = formatter;
            this.MediaType = mediaType;
        }
コード例 #3
0
 static AtomMediaType()
 {
     DefaultValue = new MediaTypeHeaderValue(MediaType);
     FeedValue = new MediaTypeHeaderValue(MediaType);
     EntryValue = new MediaTypeHeaderValue(MediaType);
     FeedValue.Parameters.Add(new NameValueHeaderValue("type", "feed"));
     FeedValue.CharSet = "utf-8";
     EntryValue.Parameters.Add(new NameValueHeaderValue("type", "entry"));
     EntryValue.CharSet = "utf-8";
     Instance = new AtomMediaType();
 }
コード例 #4
0
        /// <summary>
        /// Initializes a new instance of the <see cref="JsonContractResolver" /> class.
        /// </summary>
        /// <param name="formatter">The formatter to use for resolving required members.</param>
        public JsonContractResolver(MediaTypeFormatter formatter)
        {
            if (formatter == null)
            {
                throw Error.ArgumentNull("formatter");
            }

            _formatter = formatter;
            // Need this setting to have [Serializable] types serialized correctly
            IgnoreSerializableAttribute = false;
        }
コード例 #5
0
        /// <summary>
        /// Initializes a new instance of the <see cref="MediaTypeFormatterMatch"/> class.
        /// </summary>
        /// <param name="formatter">The matching formatter.</param>
        /// <param name="mediaType">The media type. Can be <c>null</c> in which case the media type <c>application/octet-stream</c> is used.</param>
        /// <param name="quality">The quality of the match. Can be <c>null</c> in which case it is considered a full match with a value of 1.0</param>
        /// <param name="ranking">The kind of match.</param>
        public MediaTypeFormatterMatch(MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, double? quality, MediaTypeFormatterMatchRanking ranking)
        {
            if (formatter == null)
            {
                throw Error.ArgumentNull("formatter");
            }

            this.Formatter = formatter;
            this.MediaType = mediaType != null ? mediaType.Clone() : MediaTypeConstants.ApplicationOctetStreamMediaType;
            this.Quality = quality ?? FormattingUtilities.Match;
            this.Ranking = ranking;
        }
コード例 #6
0
ファイル: ObjectContent.cs プロジェクト: bestwpw/RestBus
        /// <summary>
        /// Initializes a new instance of the <see cref="ObjectContent"/> class.
        /// </summary>
        /// <param name="type">The type of object this instance will contain.</param>
        /// <param name="value">The value of the object this instance will contain.</param>
        /// <param name="formatter">The formatter to use when serializing the value.</param>
        /// <param name="mediaType">The authoritative value of the content's Content-Type header. Can be <c>null</c> in which case the
        /// <paramref name="formatter">formatter's</paramref> default content type will be used.</param>
        public ObjectContent(Type type, object value, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType)
        {
            if (type == null)
            {
                throw Error.ArgumentNull("type");
            }
            if (formatter == null)
            {
                throw Error.ArgumentNull("formatter");
            }

            if (!formatter.CanWriteType(type))
            {
                throw Error.InvalidOperation(Properties.Resources.ObjectContent_FormatterCannotWriteType, formatter.GetType().FullName, type.Name);
            }

            _formatter = formatter;
            ObjectType = type;

            VerifyAndSetObject(value);
            _formatter.SetDefaultContentHeaders(type, Headers, mediaType);
        }
コード例 #7
0
ファイル: ObjectContent.cs プロジェクト: nuxleus/WCFWeb
 /// <summary>
 /// Forces selection of the write <see cref="MediaTypeFormatter"/> and content-type.  Used
 /// within the <see cref="HttpMessageEncodingRequestContext"/> to determine
 /// the content-type since it must be set on the <see cref="HttpResponseMessageProperty"/>
 /// before serizlization is performed in the <see cref="HttpMessageEncoder"/>.
 /// </summary>
 internal void DetermineWriteSerializerAndContentType()
 {
     this.selectedWriteFormatter = this.SelectAndValidateWriteFormatter();
 }
コード例 #8
0
        /// <summary>
        /// Pick the first supported media type and indicate we've matched only on type
        /// </summary>
        /// <param name="type">The type to be serialized.</param>
        /// <param name="formatter">The formatter we are matching against.</param>
        /// <returns>A <see cref="MediaTypeFormatterMatch"/> indicating the quality of the match or null is no match.</returns>
        protected virtual MediaTypeFormatterMatch MatchType(Type type, MediaTypeFormatter formatter)
        {
            // Performance-sensitive
            if (type == null)
            {
                throw Error.ArgumentNull("type");
            }
            if (formatter == null)
            {
                throw Error.ArgumentNull("formatter");
            }

            // We already know that we do match on type -- otherwise we wouldn't even be called --
            // so this is just a matter of determining how we match.
            MediaTypeHeaderValue mediaType = null;
            List<MediaTypeHeaderValue> supportedMediaTypes = formatter.SupportedMediaTypesInternal;
            if (supportedMediaTypes.Count > 0)
            {
                mediaType = supportedMediaTypes[0];
            }
            return new MediaTypeFormatterMatch(formatter, mediaType, FormattingUtilities.Match, MediaTypeFormatterMatchRanking.MatchOnCanWriteType);
        }
コード例 #9
0
 static ExampleMediaType()
 {
     contentType = new MediaTypeHeaderValue("application/vnd.restinpractice+xml");
     instance = new ExampleMediaType();
 }
コード例 #10
0
ファイル: MockContentNegotiator.cs プロジェクト: ymd1223/Mvc
 public new Encoding SelectResponseCharacterEncoding(HttpRequestMessage request, MediaTypeFormatter formatter)
 {
     return base.SelectResponseCharacterEncoding(request, formatter);
 }
コード例 #11
0
ファイル: MockContentNegotiator.cs プロジェクト: ymd1223/Mvc
 public new MediaTypeFormatterMatch MatchAcceptHeader(IEnumerable<MediaTypeWithQualityHeaderValue> sortedAcceptValues, MediaTypeFormatter formatter)
 {
     return base.MatchAcceptHeader(sortedAcceptValues, formatter);
 }
コード例 #12
0
ファイル: ObjectContent.cs プロジェクト: bestwpw/RestBus
 /// <summary>
 /// Initializes a new instance of the <see cref="ObjectContent"/> class.
 /// </summary>
 /// <param name="type">The type of object this instance will contain.</param>
 /// <param name="value">The value of the object this instance will contain.</param>
 /// <param name="formatter">The formatter to use when serializing the value.</param>
 public ObjectContent(Type type, object value, MediaTypeFormatter formatter)
     : this(type, value, formatter, (MediaTypeHeaderValue)null)
 {
 }
コード例 #13
0
 new public MediaTypeFormatterMatch MatchRequestMediaType(HttpRequestMessage request, MediaTypeFormatter formatter)
 {
     return base.MatchRequestMediaType(request, formatter);
 }
コード例 #14
0
 public JsonContractResolver(MediaTypeFormatter formatter)
 {
     _formatter = formatter;
     // Need this setting to have [Serializable] types serialized correctly
     IgnoreSerializableAttribute = false;
 }
コード例 #15
0
        public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
        {
            if (formatter == null)
            {
                throw new ArgumentNullException("formatter");
            }
            if (mediaType == null)
            {
                throw new ArgumentNullException("mediaType");
            }

            object sample = String.Empty;
            MemoryStream ms = null;
            HttpContent content = null;
            try
            {
                if (formatter.CanWriteType(type))
                {
                    ms = new MemoryStream();
                    content = new ObjectContent(type, value, formatter, mediaType);
                    formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
                    ms.Position = 0;
                    StreamReader reader = new StreamReader(ms);
                    string serializedSampleString = reader.ReadToEnd();
                    if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
                    {
                        serializedSampleString = TryFormatXml(serializedSampleString);
                    }
                    else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
                    {
                        serializedSampleString = TryFormatJson(serializedSampleString);
                    }

                    sample = new TextSample(serializedSampleString);
                }
                else
                {
                    sample = new InvalidSample(String.Format(
                        CultureInfo.CurrentCulture,
                        "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
                        mediaType,
                        formatter.GetType().Name,
                        type.Name));
                }
            }
            catch (Exception e)
            {
                sample = new InvalidSample(String.Format(
                    CultureInfo.CurrentCulture,
                    "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
                    formatter.GetType().Name,
                    mediaType.MediaType,
                    UnwrapException(e).Message));
            }
            finally
            {
                if (ms != null)
                {
                    ms.Dispose();
                }
                if (content != null)
                {
                    content.Dispose();
                }
            }

            return sample;
        }
コード例 #16
0
        /// <summary>
        /// Search for samples that are provided directly through <see cref="ActionSamples"/>.
        /// </summary>
        /// <param name="controllerName">Name of the controller.</param>
        /// <param name="actionName">Name of the action.</param>
        /// <param name="parameterNames">The parameter names.</param>
        /// <param name="type">The CLR type.</param>
        /// <param name="formatter">The formatter.</param>
        /// <param name="mediaType">The media type.</param>
        /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
        /// <returns>The sample that matches the parameters.</returns>
        public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
        {
            object sample;

            // First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames.
            // If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames.
            // If still not found, try to get the sample provided for the specified mediaType and type.
            // Finally, try to get the sample provided for the specified mediaType.
            if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
                ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
                ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) ||
                ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample))
            {
                return sample;
            }

            return null;
        }
        public virtual object GetActionSample(string controllerName, string actionName, IEnumerable <string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
        {
            object sample;

            if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
                ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
                ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) ||
                ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample))
            {
                return(sample);
            }

            return(null);
        }
コード例 #18
0
 public ProposalsController(IProposalOperations op)
 {
     _operations = op;
     _formatter  = new JsonMediaTypeFormatter();
 }
コード例 #19
0
ファイル: ObjectContent.cs プロジェクト: bestwpw/RestBus
 /// <summary>
 /// Initializes a new instance of the <see cref="ObjectContent"/> class.
 /// </summary>
 /// <param name="type">The type of object this instance will contain.</param>
 /// <param name="value">The value of the object this instance will contain.</param>
 /// <param name="formatter">The formatter to use when serializing the value.</param>
 /// <param name="mediaType">The authoritative value of the content's Content-Type header. Can be <c>null</c> in which case the
 /// <paramref name="formatter">formatter's</paramref> default content type will be used.</param>
 public ObjectContent(Type type, object value, MediaTypeFormatter formatter, string mediaType)
     : this(type, value, formatter, BuildHeaderValue(mediaType))
 {
 }
コード例 #20
0
 private static async Task<NameValueCollection> ReadAsAsyncCore(HttpContent content, MediaTypeFormatter[] formatters,
     CancellationToken cancellationToken)
 {
     FormDataCollection formData = await content.ReadAsAsync<FormDataCollection>(formatters, cancellationToken);
     return formData == null ? null : formData.ReadAsNameValueCollection();
 }
コード例 #21
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
            List<Encoding> supportedEncodings = formatter.SupportedEncodingsInternal;
            if (supportedEncodings.Count > 0)
            {
                // Sort Accept-Charset header values
                IEnumerable<StringWithQualityHeaderValue> sortedAcceptCharsetValues = this.SortStringWithQualityHeaderValuesByQFactor(request.Headers.AcceptCharset);

                // Check for match based on accept-charset headers
                foreach (StringWithQualityHeaderValue acceptCharset in sortedAcceptCharsetValues)
                {
                    for (int i = 0; i < supportedEncodings.Count; i++)
                    {
                        Encoding encoding = supportedEncodings[i];
                        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.Content != null ? request.Content.Headers : null);
            }

            return null;
        }
コード例 #22
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");
            }

            List<MediaTypeMapping> mediaTypeMappings = formatter.MediaTypeMappingsInternal;
            for (int i = 0; i < mediaTypeMappings.Count; i++)
            {
                MediaTypeMapping mapping = mediaTypeMappings[i];
                double quality;
                if (mapping != null && ((quality = mapping.TryMatchMediaType(request)) > FormattingUtilities.NoMatch))
                {
                    return new MediaTypeFormatterMatch(formatter, mapping.MediaType, quality, MediaTypeFormatterMatchRanking.MatchOnRequestWithMediaTypeMapping);
                }
            }

            return null;
        }
コード例 #23
0
ファイル: MockContentNegotiator.cs プロジェクト: ymd1223/Mvc
 public new MediaTypeFormatterMatch MatchType(Type type, MediaTypeFormatter formatter)
 {
     return base.MatchType(type, formatter);
 }
コード例 #24
0
        /// <summary>
        /// Match the request accept header field values against the formatter's registered supported media types.
        /// </summary>
        /// <param name="sortedAcceptValues">The sorted accept header values 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 MatchAcceptHeader(IEnumerable<MediaTypeWithQualityHeaderValue> sortedAcceptValues, MediaTypeFormatter formatter)
        {
            if (sortedAcceptValues == null)
            {
                throw Error.ArgumentNull("sortedAcceptValues");
            }
            if (formatter == null)
            {
                throw Error.ArgumentNull("formatter");
            }

            foreach (MediaTypeWithQualityHeaderValue acceptMediaTypeValue in sortedAcceptValues)
            {
                List<MediaTypeHeaderValue> supportedMediaTypes = formatter.SupportedMediaTypesInternal;
                for (int i = 0; i < supportedMediaTypes.Count; i++)
                {
                    MediaTypeHeaderValue supportedMediaType = supportedMediaTypes[i];
                    MediaTypeHeaderValueRange range;
                    if (supportedMediaType != null && acceptMediaTypeValue.Quality != FormattingUtilities.NoMatch &&
                        supportedMediaType.IsSubsetOf(acceptMediaTypeValue, out range))
                    {
                        MediaTypeFormatterMatchRanking ranking;
                        switch (range)
                        {
                            case MediaTypeHeaderValueRange.AllMediaRange:
                                ranking = MediaTypeFormatterMatchRanking.MatchOnRequestAcceptHeaderAllMediaRange;
                                break;

                            case MediaTypeHeaderValueRange.SubtypeMediaRange:
                                ranking = MediaTypeFormatterMatchRanking.MatchOnRequestAcceptHeaderSubtypeMediaRange;
                                break;

                            default:
                                ranking = MediaTypeFormatterMatchRanking.MatchOnRequestAcceptHeaderLiteral;
                                break;
                        }

                        return new MediaTypeFormatterMatch(formatter, supportedMediaType, acceptMediaTypeValue.Quality, ranking);
                    }
                }
            }

            return null;
        }
コード例 #25
0
ファイル: MockContentNegotiator.cs プロジェクト: ymd1223/Mvc
 public new MediaTypeFormatterMatch MatchMediaTypeMapping(HttpRequestMessage request, MediaTypeFormatter formatter)
 {
     return base.MatchMediaTypeMapping(request, formatter);
 }
コード例 #26
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");
            }

            if (request.Content != null)
            {
                MediaTypeHeaderValue requestMediaType = request.Content.Headers.ContentType;
                if (requestMediaType != null)
                {
                    List<MediaTypeHeaderValue> supportedMediaTypes = formatter.SupportedMediaTypesInternal;
                    for (int i = 0; i < supportedMediaTypes.Count; i++)
                    {
                        MediaTypeHeaderValue supportedMediaType = supportedMediaTypes[i];
                        if (supportedMediaType != null && supportedMediaType.IsSubsetOf(requestMediaType))
                        {
                            return new MediaTypeFormatterMatch(formatter, supportedMediaType, FormattingUtilities.Match, MediaTypeFormatterMatchRanking.MatchOnRequestMediaType);
                        }
                    }
                }
            }

            return null;
        }
コード例 #27
0
 public JsonContractResolver(MediaTypeFormatter formatter)
 {
     _formatter = formatter;
 }
コード例 #28
0
 public JsonViewContractResolver(MediaTypeFormatter formatter) : base(formatter) {
 }