This post was most recently updated on November 14th, 2021.2 min read.
This article explains how to fix an issue where your Azure Functions function (yes, that’s a capital F and a lowercase f to denote the difference between the product and the piece of compute) fails to fire when a POST request comes in, even though it’s configured to do so, and instead throws a somewhat confusing error message about HttpRequestMessage not being castable to HttpRequest – even though you KNOW HttpRequestMessage works just fine for receiving POST requests with payload!
So, why is this happening and how do you fix it?
The error, thrown in Azure Functions CLI, is as follows:
Unable to cast object of type 'System.Net.Http.HttpRequestMessage' to type 'Microsoft.AspNetCore.Http.HttpRequest'.
This seems to have been caused by HttpRequestMessage not working with… Well, Azure Functions. At least not when being bound as an input.
So if you’re like me and you’re just copy-pasting stuff from another one of your projects (code reuse at its best, am I right?), you’ll need to change that. Let’s see how!
Not as complicated as you might have feared.
Time needed: 5 minutes.
How to fix “Unable to cast object of type System.Net.Http.HttpRequestMessage to type Microsoft.AspNetCore.Http.HttpRequest.” in 3 simple steps?
- Change the HttpTrigger from HttpRequestMessage to HttpRequest
So change it from this:
- Add a reference to System.Text.Json (and System.IO just in case)
Add a new using statement for your function – you’ll need System.Text.Json for the next step if you’re parsing the POST body as an object, and System.IO if you’re parsing strings, in the next step.
- Change the way you read the body
You might have something like this:
MyClass obj = await req.Content.ReadAsAsync<MyClass>();
Change it to look like this:
MyClass obj = await JsonSerializer.DeserializeAsync<MyClass>(req.Body);
Or to something like this, if it’s just a string:
string content= await new StreamReader(req.Body).ReadToEndAsync();
- Rebuild and you should be good
Did it help? Let me know in the comments section below!
- Azure Function build fails with “Mono.Cecil.AssemblyResolutionException: Failed to resolve assembly: Microsoft.AspNetCore.Mvc.Core” - December 1, 2021
- How to update from deprecated Microsoft.Azure.Services.AppAuthentication to new and shiny Azure.Security.KeyVaults.Secrets? - November 23, 2021
- Fixing Blazor WebAssembly .NET 6 MSAL authorization bug - November 16, 2021