Dealing with Optional Content in an Azure Function





5.00/5 (1 vote)
Fix the 500 error if no Content-Type is specified
Introduction
If you call an Azure function that has Content.ReadAsAsync
with no Content-Type
header, it will fail with a 500 error. This allows you to skip over that if no content is specified.
Using the Code
In the Azure function body, put the ReadAsAsync
in two nested null
traps thus:
ExistingBalanceData priorBalance = null;
if (req.Content != null)
{
if (! (req.Content.Headers.ContentType == null))
{
priorBalance = await req.Content.ReadAsAsync<ExistingBalanceData>();
}
}
The first will deal with cases where no content is sent, the second where no Content-Type
header has been set - some clients seem to do this to indicate that there is no content.
History
- 17th November, 2020: Initial version