'Http Post to .net isolated azure function Body Empty (most) of the time
I am executing the following:
HttpClient _httpClient= new HttpClient
{
BaseAddress = new Uri("http://localhost:7071/api/"), // Local
Timeout = TimeSpan.FromSeconds(60)
};
_httpClient.DefaultRequestHeaders.Accept.Clear();
_httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var stopMessage = new Domain.StopMessage
{
SiteId = "SiteId",
};
var response = await _httpClient.PostAsJsonAsync("StopMessage", stopMessage);
Against this function:
[Function("StopMessage")]
public async Task<HttpResponseData> Run([HttpTrigger(AuthorizationLevel.Anonymous, "post")] HttpRequestData req, FunctionContext executionContext)
{
var log = executionContext.GetLogger(nameof(StopMessage));
try
{
DateTime currentDate = DateTime.Now;
string requestBody = string.Empty;
using (StreamReader streamReader = new StreamReader(req.Body))
{
requestBody = await streamReader.ReadToEndAsync();
}
I am using a .net isolated function. Here is my host.json:
{
"version": "2.0",
"logging": {
"applicationInsights": {
"samplingSettings": {
"isEnabled": true,
"excludedTypes": "Request"
}
}
},
"functionTimeout": "00:05:00",
"extensions": {
"eventHubs": {
"batchCheckpointFrequency": 5,
"eventProcessorOptions": {
"maxBatchSize": 256,
"prefetchCount": 512
},
"initialOffsetOptions": {
"type": "fromEnqueuedTime",
"enqueuedTimeUtc": "2021-11-01T00:00Z"
}
}
},
// Configuration settings for Singleton lock behavior. (Optional)
"singleton": {
// The period that function level locks are taken for (they will auto renew)
"lockPeriod": "00:01:00"
}
}
75% of the time requestBody is empty and the transfer is not made. I can repeat send the same request multiple times and sometimes it will populate the body and sometimes it won't. How can I make it that it the body is always present?
Solution 1:[1]
The issue seem to be between _httpClient.PostAsJsonAsync("StopMessage", stopMessage);
and HttpRequestData
I can not give you the reason to why this issue occours.
But if JsonSerializer.Serialize
is used it seems to work fine.
string json = JsonSerializer.Serialize(stopMessage);
var httpResponseMessage = await _httpClient.PostAsync("StopMessage", new StringContent(json));
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Anders Urban |