Azure Functions CLI - such a pretty logo for such an awesome functionality

How to fix “Unable to cast object of type ‘System.Net.Http.HttpRequestMessage’ to type ‘Microsoft.AspNetCore.Http.HttpRequest’.”

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?

Problem

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!

Solution

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?

  1. Change the HttpTrigger from HttpRequestMessage to HttpRequest

    So change it from this:
    HttpRequestMessage req

    To this:
    HttpRequest req

  2. 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.

  3. 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();

  4. Rebuild and you should be good

    Gerald Butler GIFs | Tenor


Did it help? Let me know in the comments section below!

mm
0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments