forked from Pathoschild/FluentHttpClient
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path<
8000
/span>Factory.cs
More file actions
50 lines (44 loc) · 2.3 KB
/
Factory.cs
File metadata and controls
50 lines (44 loc) · 2.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
using System;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
namespace Pathoschild.Http.Client.Internal
{
/// <summary>Internal helper for constructing instances.</summary>
internal static class Factory
{
/*********
** Public methods
*********/
/***
** HttpClient
***/
/// <summary>Get the formatter for an HTTP content type.</summary>
/// <param name="formatters">The formatters used for serializing and deserializing message bodies.</param>
/// <param name="contentType">The HTTP content type (or <c>null</c> to automatically select one).</param>
/// <exception cref="InvalidOperationException">
4D81
;No MediaTypeFormatters are available on the API client for this content type.</exception>
public static MediaTypeFormatter GetFormatter(MediaTypeFormatterCollection formatters, MediaTypeHeaderValue contentType = null)
{
if (!formatters.Any())
throw new InvalidOperationException("No MediaTypeFormatters are available on the fluent client.");
MediaTypeFormatter formatter = contentType != null
? formatters.FirstOrDefault(f => f.SupportedMediaTypes.Any(m => m.MediaType == contentType.MediaType))
: formatters.FirstOrDefault();
if (formatter == null)
throw new InvalidOperationException(String.Format("No MediaTypeFormatters are available on the fluent client for the '{0}' content-type.", contentType));
return formatter;
}
/// <summary>Construct an HTTP request message.</summary>
/// <param name="method">The HTTP method.</param>
/// <param name="resource">The URI to send the request to.</param>
/// <param name="formatters">The formatters used for serializing and deserializing message bodies.</param>
public static HttpRequestMessage GetRequestMessage(HttpMethod method, Uri resource, MediaTypeFormatterCollection formatters)
{
HttpRequestMessage request = new HttpRequestMessage(method, resource);
// add default headers
request.Headers.Add("accept", formatters.SelectMany(p => p.SupportedMediaTypes).Select(p => p.MediaType));
return request;
}
}
}