-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathFormParam.cs
More file actions
73 lines (67 loc) · 2.9 KB
/
FormParam.cs
File metadata and controls
73 lines (67 loc) · 2.9 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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
// <copyright file="FormParam.cs" company="APIMatic">
// Copyright (c) APIMatic. All rights reserved.
// </copyright>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using APIMatic.Core.Http.Configuration;
using APIMatic.Core.Types;
using APIMatic.Core.Types.Sdk;
using APIMatic.Core.Utilities;
namespace APIMatic.Core.Request.Parameters
{
/// <summary>
/// Form parameter class used to send a request parameter in form
/// </summary>
public class FormParam : Parameter
{
private readonly Dictionary<string, string> encodingHeaders = new Dictionary<string, string>();
internal FormParam() => typeName = "form";
public FormParam EncodingHeader(string key, string value)
{
encodingHeaders[key.ToLower()] = value;
return this;
}
private bool IsMultipart() => encodingHeaders.TryGetValue("content-type", out var contentType)
&& contentType != ContentType.FORM_URL_ENCODED.GetValue();
private void AddEncodingHeaders(Dictionary<string, IReadOnlyCollection<string>> headers)
{
if (encodingHeaders.TryGetValue("content-type", out var contentType))
{
headers["content-type"] = new[] { contentType };
}
}
private IEnumerable<KeyValuePair<string, object>> PrepareFormParameters(ArraySerialization arraySerialization)
{
var multipartHeaders = new Dictionary<string, IReadOnlyCollection<string>>(StringComparer.OrdinalIgnoreCase);
if (value is CoreFileStreamInfo file)
{
var defaultFileContentType = string.IsNullOrEmpty(file.ContentType) ? ContentType.BINARY.GetValue() : file.ContentType;
multipartHeaders["content-type"] = new[] { defaultFileContentType };
AddEncodingHeaders(multipartHeaders);
return new List<KeyValuePair<string, object>>
{
new KeyValuePair<string, object>(key, new MultipartFileContent(file, multipartHeaders))
};
}
if (IsMultipart())
{
AddEncodingHeaders(multipartHeaders);
return new List<KeyValuePair<string, object>>
{
new KeyValuePair<string, object>(key, new MultipartByteArrayContent(Encoding.ASCII.GetBytes(CoreHelper.JsonSerialize(value)), multipartHeaders))
};
}
return CoreHelper.PrepareFormFieldsFromObject(key, value, arraySerializationFormat: arraySerialization).Where(kv => kv.Value != null);
}
internal override void Apply(RequestBuilder requestBuilder)
{
if (!validated || value == null)
{
return;
}
requestBuilder.formParameters.AddRange(PrepareFormParameters(requestBuilder.ArraySerialization));
}
}
}