Skip to content
This repository was archived by the owner on Feb 17, 2023. It is now read-only.
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
146 changes: 146 additions & 0 deletions src/targets/csharp/httpclient.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,146 @@
'use strict'

var CodeBuilder = require('../../helpers/code-builder')

function getDecompressionMethods (source) {
var acceptEncoding = source.allHeaders['accept-encoding']
if (!acceptEncoding) {
return [] // no decompression
}

var supportedMethods = {
gzip: 'DecompressionMethods.GZip',
deflate: 'DecompressionMethods.Deflate'
}
var methods = []
acceptEncoding.split(',').forEach(function (encoding) {
var match = /\s*([^;\s]+)/.exec(encoding)
if (match) {
var method = supportedMethods[match[1]]
if (method) {
methods.push(method)
}
}
})

return methods
}

module.exports = function (source, options) {
var indentation = ' '
var code = new CodeBuilder(indentation)

var clienthandler = ''
var cookies = !!source.allHeaders.cookie
var decompressionMethods = getDecompressionMethods(source)
if (cookies || decompressionMethods.length) {
clienthandler = 'clientHandler'
code.push('var clientHandler = new HttpClientHandler')
code.push('{')
if (cookies) {
// enable setting the cookie header
code.push(1, 'UseCookies = false,')
}
if (decompressionMethods.length) {
// enable decompression for supported methods
code.push(1, 'AutomaticDecompression = %s,', decompressionMethods.join(' | '))
}
code.push('};')
}

code.push('var client = new HttpClient(%s);', clienthandler)

code.push('var request = new HttpRequestMessage')
code.push('{')

var methods = [ 'GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'HEAD', 'OPTIONS', 'TRACE' ]
var method = source.method.toUpperCase()
if (method && (methods.indexOf(method) !== -1)) {
// buildin method
method = `HttpMethod.${method[0]}${method.substring(1).toLowerCase()}`
} else {
// custom method
method = `new HttpMethod("${method}")`
}
code.push(1, 'Method = %s,', method)

code.push(1, 'RequestUri = new Uri("%s"),', source.fullUrl)

var headers = Object.keys(source.allHeaders).filter(function (header) {
switch (header) {
case 'content-type':
case 'content-length':
case 'accept-encoding':
// skip these headers
return false
default:
return true
}
})
if (headers.length) {
code.push(1, 'Headers =')
code.push(1, '{')
headers.forEach(function (key) {
code.push(2, '{ "%s", "%s" },', key, source.allHeaders[key])
})
code.push(1, '},')
}

if (source.postData.text) {
const contentType = source.postData.mimeType
switch (contentType) {
case 'application/x-www-form-urlencoded':
code.push(1, 'Content = new FormUrlEncodedContent(new Dictionary<string, string>')
code.push(1, '{')
source.postData.params.forEach(function (param) {
code.push(2, '{ "%s", "%s" },', param.name, param.value)
})
code.push(1, '}),')
break
case 'multipart/form-data':
code.push(1, 'Content = new MultipartFormDataContent')
code.push(1, '{')
source.postData.params.forEach(function (param) {
code.push(2, 'new StringContent(%s)', JSON.stringify(param.value || ''))
code.push(2, '{')
code.push(3, 'Headers =')
code.push(3, '{')
if (param.contentType) {
code.push(4, 'ContentType = new MediaTypeHeaderValue("%s"),', param.contentType)
}
code.push(4, 'ContentDisposition = new ContentDispositionHeaderValue("form-data")')
code.push(4, '{')
code.push(5, 'Name = "%s",', param.name)
if (param.fileName) {
code.push(5, 'FileName = "%s",', param.fileName)
}
code.push(4, '}')
code.push(3, '}')
code.push(2, '},')
})

code.push(1, '},')
break
default:
code.push(1, 'Content = new StringContent(%s, Encoding.UTF8, "%s")', JSON.stringify(source.postData.text || ''), contentType)
break
}
}
code.push('};')

// send and read response
code.push('using (var response = await client.SendAsync(request))')
code.push('{')
code.push(1, 'response.EnsureSuccessStatusCode();')
code.push(1, 'var body = await response.Content.ReadAsStringAsync();')
code.push('}')

return code.join()
}

module.exports.info = {
key: 'httpclient',
title: 'HttpClient',
link: 'https://docs.microsoft.com/en-us/dotnet/api/system.net.http.httpclient',
description: '.NET Standard HTTP Client'
}
5 changes: 3 additions & 2 deletions src/targets/csharp/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,9 @@ module.exports = {
key: 'csharp',
title: 'C#',
extname: '.cs',
default: 'restsharp'
default: 'httpclient'
},

restsharp: require('./restsharp')
restsharp: require('./restsharp'),
httpclient: require('./httpclient')
}
8 changes: 7 additions & 1 deletion test/fixtures/available-targets.json
Original file line number Diff line number Diff line change
Expand Up @@ -217,13 +217,19 @@
"key": "csharp",
"title": "C#",
"extname": ".cs",
"default": "restsharp",
"default": "httpclient",
"clients": [
{
"key": "restsharp",
"title": "RestSharp",
"link": "http://restsharp.org/",
"description": "Simple REST and HTTP API Client for .NET"
},
{
"key": "httpclient",
"title": "HttpClient",
"link": "https://docs.microsoft.com/en-us/dotnet/api/system.net.http.httpclient",
"description": ".NET Standard HTTP Client"
}
]
},
Expand Down
16 changes: 16 additions & 0 deletions test/fixtures/output/csharp/httpclient/application-form-encoded.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
var client = new HttpClient();
var request = new HttpRequestMessage
{
Method = HttpMethod.Post,
RequestUri = new Uri("http://mockbin.com/har"),
Content = new FormUrlEncodedContent(new Dictionary<string, string>
{
{ "foo", "bar" },
{ "hello", "world" },
}),
};
using (var response = await client.SendAsync(request))
{
response.EnsureSuccessStatusCode();
var body = await response.Content.ReadAsStringAsync();
}
12 changes: 12 additions & 0 deletions test/fixtures/output/csharp/httpclient/application-json.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
var client = new HttpClient();
var request = new HttpRequestMessage
{
Method = HttpMethod.Post,
RequestUri = new Uri("http://mockbin.com/har"),
Content = new StringContent("{\"number\":1,\"string\":\"f\\\"oo\",\"arr\":[1,2,3],\"nested\":{\"a\":\"b\"},\"arr_mix\":[1,\"a\",{\"arr_mix_nested\":{}}],\"boolean\":false}", Encoding.UTF8, "application/json")
};
using (var response = await client.SendAsync(request))
{
response.EnsureSuccessStatusCode();
var body = await response.Content.ReadAsStringAsync();
}
19 changes: 19 additions & 0 deletions test/fixtures/output/csharp/httpclient/cookies.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
var clientHandler = new HttpClientHandler
{
UseCookies = false,
};
var client = new HttpClient(clientHandler);
var request = new HttpRequestMessage
{
Method = HttpMethod.Post,
RequestUri = new Uri("http://mockbin.com/har"),
Headers =
{
{ "cookie", "foo=bar; bar=baz" },
},
};
using (var response = await client.SendAsync(request))
{
response.EnsureSuccessStatusCode();
var body = await response.Content.ReadAsStringAsync();
}
11 changes: 11 additions & 0 deletions test/fixtures/output/csharp/httpclient/custom-method.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
var client = new HttpClient();
var request = new HttpRequestMessage
{
Method = new HttpMethod("PROPFIND"),
RequestUri = new Uri("http://mockbin.com/har"),
};
using (var response = await client.SendAsync(request))
{
response.EnsureSuccessStatusCode();
var body = await response.Content.ReadAsStringAsync();
}
24 changes: 24 additions & 0 deletions test/fixtures/output/csharp/httpclient/full.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
var clientHandler = new HttpClientHandler
{
UseCookies = false,
};
var client = new HttpClient(clientHandler);
var request = new HttpRequestMessage
{
Method = HttpMethod.Post,
RequestUri = new Uri("http://mockbin.com/har?foo=bar&foo=baz&baz=abc&key=value"),
Headers =
{
{ "cookie", "foo=bar; bar=baz" },
{ "accept", "application/json" },
},
Content = new FormUrlEncodedContent(new Dictionary<string, string>
{
{ "foo", "bar" },
}),
};
using (var response = await client.SendAsync(request))
{
response.EnsureSuccessStatusCode();
var body = await response.Content.ReadAsStringAsync();
}
16 changes: 16 additions & 0 deletions test/fixtures/output/csharp/httpclient/headers.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
var client = new HttpClient();
var request = new HttpRequestMessage
{
Method = HttpMethod.Get,
RequestUri = new Uri("http://mockbin.com/har"),
Headers =
{
{ "accept", "application/json" },
{ "x-foo", "Bar" },
},
};
using (var response = await client.SendAsync(request))
{
response.EnsureSuccessStatusCode();
var body = await response.Content.ReadAsStringAsync();
}
11 changes: 11 additions & 0 deletions test/fixtures/output/csharp/httpclient/https.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
var client = new HttpClient();
var request = new HttpRequestMessage
{
Method = HttpMethod.Get,
RequestUri = new Uri("https://mockbin.com/har"),
};
using (var response = await client.SendAsync(request))
{
response.EnsureSuccessStatusCode();
var body = await response.Content.ReadAsStringAsync();
}
12 changes: 12 additions & 0 deletions test/fixtures/output/csharp/httpclient/jsonObj-multiline.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
var client = new HttpClient();
var request = new HttpRequestMessage
{
Method = HttpMethod.Post,
RequestUri = new Uri("http://mockbin.com/har"),
Content = new StringContent("{\n \"foo\": \"bar\"\n}", Encoding.UTF8, "application/json")
};
using (var response = await client.SendAsync(request))
{
response.EnsureSuccessStatusCode();
var body = await response.Content.ReadAsStringAsync();
}
12 changes: 12 additions & 0 deletions test/fixtures/output/csharp/httpclient/jsonObj-null-value.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
var client = new HttpClient();
var request = new HttpRequestMessage
{
Method = HttpMethod.Post,
RequestUri = new Uri("http://mockbin.com/har"),
Content = new StringContent("{\"foo\":null}", Encoding.UTF8, "application/json")
};
using (var response = await client.SendAsync(request))
{
response.EnsureSuccessStatusCode();
var body = await response.Content.ReadAsStringAsync();
}
26 changes: 26 additions & 0 deletions test/fixtures/output/csharp/httpclient/multipart-data.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
var client = new HttpClient();
var request = new HttpRequestMessage
{
Method = HttpMethod.Post,
RequestUri = new Uri("http://mockbin.com/har"),
Content = new MultipartFormDataContent
{
new StringContent("Hello World")
{
Headers =
{
ContentType = new MediaTypeHeaderValue("text/plain"),
ContentDisposition = new ContentDispositionHeaderValue("form-data")
{
Name = "foo",
FileName = "hello.txt",
}
}
},
},
};
using (var response = await client.SendAsync(request))
{
response.EnsureSuccessStatusCode();
var body = await response.Content.ReadAsStringAsync();
}
26 changes: 26 additions & 0 deletions test/fixtures/output/csharp/httpclient/multipart-file.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
var client = new HttpClient();
var request = new HttpRequestMessage
{
Method = HttpMethod.Post,
RequestUri = new Uri("http://mockbin.com/har"),
Content = new MultipartFormDataContent
{
new StringContent("")
{
Headers =
{
ContentType = new MediaTypeHeaderValue("text/plain"),
ContentDisposition = new ContentDispositionHeaderValue("form-data")
{
Name = "foo",
FileName = "test/fixtures/files/hello.txt",
}
}
},
},
};
using (var response = await client.SendAsync(request))
{
response.EnsureSuccessStatusCode();
var body = await response.Content.ReadAsStringAsync();
}
Loading