This repository has been archived by the owner on Nov 8, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathcsharp.html
65 lines (61 loc) · 2.8 KB
/
csharp.html
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
<section name="csharp" class="csharp">
<p class="ioDesc">Request</p>
<pre class="incoming"><code class="language-csharp">
//Common testing requirement. If you are consuming an API in a sandbox/test region, uncomment this line of code ONLY for non production uses.
//System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
//Be sure to run "Install-Package Microsoft.Net.Http" from your nuget command line.
using System;
using System.Net.Http;
var baseAddress = new Uri("<%- @apiUrl + "/" %>");
using (var httpClient = new HttpClient{ BaseAddress = baseAddress })
{
<% if @helpers.isNotEmpty @headers: %>
<% for header, value of @headers: %><% header = header.toLowerCase() %>
<% if header not in ['content-type', 'content-length']: %>
httpClient.DefaultRequestHeaders.TryAddWithoutValidation("<%- header %>", "<%- value %>");
<% else if header is 'content-type': %>
<% @content_type = value %>
<% end %>
<% end %>
<% end %>
<% if @method in ['GET', 'DELETE', 'OPTIONS', 'HEAD']: %>
<% if @method is 'HEAD': %>
var requestUri = new Uri(baseAddress, "<%= @url.substring(1) %>");
using (var request = new HttpRequestMessage { Method = new HttpMethod("<%- @method.toUpperCase() %>"), RequestUri = requestUri })
{
using (var response = await httpClient.SendAsync(request))
{
<% else: %>
using(var response = await httpClient.<%- @method.charAt(0).toUpperCase() + @method.substring(1).toLowerCase() %>Async("<%= @url.substring(1) %>"))
{
<% end: %>
<% else: %>
<% if !@body?: %>
<% @body = "" %>
<% end: %>
<% if @content_type? : %>
using (var content = new StringContent("<%- @helpers.escape @body %>", System.Text.Encoding.Default, "<%- @content_type %>"))
<% else : %>
using (var content = new StringContent("<%- @helpers.escape @body %>"))
<% end %>
{
<% if @method in ['POST', 'PUT']: %>
using (var response = await httpClient.<%- @method.charAt(0).toUpperCase() + @method.substring(1).toLowerCase() %>Async("<%= @url.substring(1) %>", content))
{
<% else : %>
using (HttpResponseMessage response = null)
{
var requestUri = new Uri(baseAddress, "<%= @url.substring(1) %>");
using (var request = new HttpRequestMessage{ Method = new HttpMethod("<%- @method.toUpperCase() %>"), RequestUri = requestUri, Content = content })
{
response = await httpClient.SendAsync(request);
}
<% end %>
<% end %>
string responseData = await response.Content.ReadAsStringAsync();
<% if @method in ['POST', 'PUT', 'HEAD']: %>
}
<% end %>
}
}
</code></pre></section>