This post was most recently updated on February 7th, 2022.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!
- How to fix OnePlus 10 Pro Bluetooth issues - May 23, 2023
- How to actually uninstall conflicting PowerShell modules? - May 16, 2023
- How to enable Developer Mode on Android? - May 9, 2023