Skip to main content

HTTP Payload - C Sharp

The logic payload type when a task is invoked by an API Route trigger.

Class Reference

Type

Properties

PropertyTypeDescription
ApiGatewayIdentityContextIdentityContextAPI gateway permanent ID and name
ApiRouteIdentityContextIdentityContextAPI route permanent ID and name
RequestIdstringRequest ID
RequestHttpRequestRequest content
SourcePeer?Request source
DestinationPeer?Request destination

IdentityContext

PropertyTypeDescription
PermanentIdentityGuidIdentity permanent ID
NamestringIdentity name

Peer

PropertyTypeDescription
AddressAddressPeer address

Address

PropertyType
Protocolstring
Addressbyte[]
Portuint

HttpRequest

Data and metadata of the HTTP request.

PropertyTypeDescriptionExample
HoststringRequest host name
PathstringAPI route/api/path
SchemestringHTTP schemehttp, https
MethodstringHTTP methodGET, POST, etc.
VersionstringHTTP versionHTTP/1.1
HeadersDictionary<byte[], byte[]>Request headers
QuerystringQuerystringparam1=value1 (no question mark; empty string if no querystring available)
Databyte[]Request body (empty array if not available)

Examples

Parse Querystring

Assuming the querystring is

`?name=Arthur+Dent&age=42`

The parameters can be parsed as below:

Import namespace(s)
using System.Web;
using System.Collections.Specialized;
var payload = await ctx.GetPayload();

string? queryString = payload.Http?.Request.Query;
NameValueCollection? queryParams = null;

if (!String.IsNullOrWhiteSpace(queryString)) {
queryParams = HttpUtility.ParseQueryString(queryString);
}

string? name = queryParams?["name"]; // null if not exist
int age = Convert.ToInt32(queryParams?["age"]); // 0 if not exist

Parse HTTP Payload body to JSON

Assuming the HTTP request includes a body with the following JSON string:

{
"name": "Arthur Dent",
"age": 42,
"job": {
"title": "Sandwich-maker",
"salary": 0
},
"quotes": [
"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?"
]
}

We can parse the payload into a JsonNode object, if the content of the payload may not be fixed (with its elements automatically parsed as JsonValue, JsonObject or JsonArray):

Import namespace(s)
using System.Text;
using System.Text.Json.Nodes;
var payload = await ctx.GetPayload();

byte[]? data = payload.Http?.Request.Data;
JsonNode? parsed = null;

if (data is not null && data.Length > 0)
{
string jsonString = Encoding.UTF8.GetString(data);
parsed = JsonNode.Parse(jsonString); // will fail if jsonString is not valid JSON
}

// get values (null if not exist)
string? name = parsed?["name"]?.GetValue<string>();
int? age = parsed?["age"]?.GetValue<int>();

// ...

See the example of Payload for checking the payload type.

See the example of session storage agent for how to use classes extended from JsonNode.

Advanced Examples

Parse HTTP Payload Into User-Defined Classes

Assuming the HTTP request includes a body as the previous example but always be fixed, we can define classes to match the data structure, which require a source generation context class for it to be deserialised properly:

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.

Then you can parse the HTTP payload into a Person object using JsonSerializer.Deserialize():

var payload = await ctx.GetPayload();

byte[]? data = payload.Http?.Request.Data;
Person? person = null;

if (data is not null && data.Length > 0)
{
string jsonString = Encoding.UTF8.GetString(data);
person = JsonSerializer.Deserialize<Person>(
jsonString,
PersonSourceGenerationContext.Default.Person
);
}

if (person is not null)
{
// read values from properties
string name = person.name;
int age = person.age;
string title = person.job.title;
List<string> quotes = person.quotes;
}