// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Specialized; using System.ComponentModel; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Threading; using System.Threading.Tasks; using System.Web.Http; #if NETFX_CORE using NameValueCollection = System.Net.Http.Formatting.HttpValueCollection; #endif namespace System.Net.Http { /// /// Extension methods to allow HTML form URL-encoded data, also known as application/x-www-form-urlencoded, /// to be read from instances. /// [EditorBrowsable(EditorBrowsableState.Never)] public static class HttpContentFormDataExtensions { private const string ApplicationFormUrlEncoded = "application/x-www-form-urlencoded"; /// /// Determines whether the specified content is HTML form URL-encoded data, also known as application/x-www-form-urlencoded data. /// /// The content. /// /// true if the specified content is HTML form URL-encoded data; otherwise, false. /// public static bool IsFormData(this HttpContent content) { if (content == null) { throw Error.ArgumentNull("content"); } MediaTypeHeaderValue contentType = content.Headers.ContentType; return contentType != null && String.Equals(ApplicationFormUrlEncoded, contentType.MediaType, StringComparison.OrdinalIgnoreCase); } /// /// Returns a that will yield a instance containing the form data /// parsed as HTML form URL-encoded from the instance. /// /// The content. /// A which will provide the result. If the data can not be read /// as HTML form URL-encoded data then the result is null. public static Task ReadAsFormDataAsync(this HttpContent content) { return ReadAsFormDataAsync(content, CancellationToken.None); } /// /// Returns a that will yield a instance containing the form data /// parsed as HTML form URL-encoded from the instance. /// /// The content. /// The token to monitor for cancellation requests. /// A which will provide the result. If the data can not be read /// as HTML form URL-encoded data then the result is null. public static Task 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); } private static async Task ReadAsAsyncCore(HttpContent content, MediaTypeFormatter[] formatters, CancellationToken cancellationToken) { FormDataCollection formData = await content.ReadAsAsync(formatters, cancellationToken); return formData == null ? null : formData.ReadAsNameValueCollection(); } } }