Skip to main content

HTTP Agent - C Sharp

Send HTTP request to a HTTP endpoint and fetch the response.

Logic TypeAvailable
Generic logic
Aggregator logic

HTTP Agent Configuration

See: Agent Configuration

A HTTP Agent Configuration defines an external HTTP host that will be allowed to be accessed from LOC runtime.

The HTTP Agent requires a configuration reference name so that it can access external endpoints on the host. The reference name can be added to a logic while creating or editing a data process.

Import and Usage

The agent can be used without using additional namespaces:

public static class Logic
{

public static async Task Run(Context ctx)
{
var httpClient = await HttpAgent.Acquire("http-config-ref");
var response = await httpClient.Send("/api/path");
}

public static async Task HandleError(Context ctx, Exception error)
{
// ... same
}
}

Class Reference

Type

  • HttpAgent

Method: Acquire HTTP Client

public async static Task<HttpClient> Acquire(string name) {}
ParameterDescription
nameHTTP Agent Configuration reference name

Acquire a HTTP client using a configuration reference name. Throws an error if the configuration cannot be found.

HTTP Client

Type

  • Public static class HttpClient

Methods: Send HTTP Request

public async Task<HttpResponseMessage> Post(string path) {}
public async Task<HttpResponseMessage> Post(SendHttpRequest request) {}
ParametersTypeDescription
pathstringHTTP request path (no host)
requestSendHttpRequestHTTP request parameters

Send HTTP request to a HTTP endpoint. Returns a HttpResponseMessage object.

info

The URL can only contain the path (without host name, which is already in the HTTP Agent Configuration).

The path can contain querystring.

SendHttpRequest

HTTP request parameters, including path and method.

Properties:

PropertyTypeDescription
PathstringHTTP request path
MethodHttpMethodHTTP request method
HeadersHttpContentHeadersHTTP request headers
BodyStreamStreamHTTP request body
BodyLengthulongHTTP request body length
info

All HTTP agent client methods will set the method parameter automatically. You don't need to set it manually.

Constructors:

public SendHttpRequest(string path)
public SendHttpRequest(
string path, // Path
HttpContent content
)

The second constructor accepts a HttpContent object, which can define the request body, encoding and content type.

HttpContent

Refer to: HttpContent. See here for available HTTP content types.

HttpResponseMessage

Refer to: HttpResponseMessage.

The Content property is HttpContent class and Headers is HttpResponseHeaders class.

Examples

GET Request with Querystring

const string queryString = "name=Arthur+Dent&age=42";

/* or:
// using System.Web;
// using System.Collections.Specialized;

NameValueCollection queryParams = HttpUtility.ParseQueryString("");
queryParams.Add("name", "Arthur+Dent");
queryParams.Add("age", $"{42}");

const string queryString = queryParams.ToString();
*/

var httpClient = await HttpAgent.Acquire("http-config-ref");

var response = await httpClient.Get($"/api/path?{queryString}");

// if the response status is 2xx
if (response.IsSuccessStatusCode) {
// ...
}

POST Request and Parse Response

Import namespace(s)
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
var data = new JsonObject
{
["name"] = "Arthur Dent",
["age"] = 42,
["job"] = new JsonObject
{
["title"] = "Sandwich-maker",
["salary"] = 0
},
["quotes"] = new JsonArray(
"Is there any tea on this spaceship?",
"This must be Thursday. I never could get the hang of Thursdays.",
"Would it save you a lot of time if I just gave up and went mad now?"
),
};

var httpClient = await HttpAgent.Acquire("http-config-ref");

var response = await httpClient.Post(new SendHttpRequest(
"/api/path",
new StringContent(
data.ToJsonString(), // convert body to string
Encoding.UTF8, // encoding
"application/json" // content type
)
));

// get HTTP response status code
int statusCode = (int) response.StatusCode;

// get headers
string authorization = "";
if (response.Headers.Contains("Authorization")){
authorization = response.Headers.GetValues("Authorization").First().ToString();
}
string contentType = "";
if (response.Headers.Contains("Content-Type")){
contentType = response.Headers.GetValues("Content-Type").First().ToString();
}

// if the response status is 2xx
string? body = null;
JsonNode? json = null;
if (response.IsSuccessStatusCode)
{

// get response body as string
body = await response.Content.ReadAsStringAsync();

// try parse the body to JSON:
json = JsonNode.Parse(body);

// ...
}

Advanced Examples

POST Request Using User-Defined Classes

We can also serialise user-defined classes as the POST request body:

Import namespace(s) and declare classes
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;

internal class Person
{
[JsonPropertyName("name")]
public string? Name { get; set; }

[JsonPropertyName("age")]
public int? Age { get; set; }

[JsonPropertyName("job")]
public Job? Job { get; set; }

[JsonPropertyName("quotes")]
public List<string>? Quotes { get; set; }

public Person(string name, int age, Job job, List<string> quotes)
{
Name = name;
Age = age;
Job = job;
Quotes = quotes;
}
}

internal class Job
{
[JsonPropertyName("title")]
public string? Title { get; set; }

[JsonPropertyName("salary")]
public int? Salary { get; set; }

public Job(string title, int salary)
{
Title = title;
Salary = salary;
}
}

// source generation context for Person
[JsonSourceGenerationOptions()]
[JsonSerializable(typeof(Person))]
internal partial class PersonSourceGenerationContext : JsonSerializerContext
{
}
info

You can move user-defined classes into shared modules as public classes. See the tutorial for examples.

Person person = new(
"Arthur Dent",
42,
new Job(
"Sandwich-maker",
0
),
new List<string>()
{
"Is there any tea on this spaceship?",
"This must be Thursday. I never could get the hang of Thursdays.",
"Would it save you a lot of time if I just gave up and went mad now?"
}
);

var httpClient = await HttpAgent.Acquire("http-config-ref");

var response = await httpClient.Post(new SendHttpRequest(
"/api/path",
new StringContent(
JsonSerializer.Serialize<Person>(
person,
PersonSourceGenerationContext.Default.Person
), // convert class to string using source generation context
Encoding.UTF8, // encoding
"application/json" // content type
)
));

// ...