Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Azure Functions model binding

I've created an Azure Function and I'm running it locally:

[FunctionName("HttpTriggerCSharpSet")]
public static async Task<HttpResponseMessage> Set([HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] MyDocument req, TraceWriter log)
{
   // ...
}

Notice that MyDocument is the first parameter instead of HttpRequestMessage. I've read in the documentation that this approach should work, and it seems very similar to ASP.NET model binding (in my mind, anyway). MyDocument is a POCO with just 3 properties.

public class MyDocument
{
    public string Name { get; set; }
    public int ShoeSize { get; set; }
    public decimal Balance { get; set; }
}

When I POST to the function like so (I'm using Postman):

POST with Postman to Azure Function

I get an error message: [8/8/2017 2:21:07 PM] Exception while executing function: Functions.HttpTriggerCSharpSet. Microsoft.Azure.WebJobs.Host: Exception binding parameter 'req'. System.Net.Http.Formatting: No MediaTypeFormatter is available to read an object of type 'MyDocument' from content (which you can also see in the screenshot of Postman above)

I've tried form-data and x-www-form-urlencoded and even raw from Postman, same error every time. I've also tried switching back to HttpRequestMessage and using req.Content.ReadAsAsync<MyDocument>, and I get a similar error. Am I constructing my POST incorrectly, or am I writing my Azure Function incorrectly. In either case, what's the correct way?

like image 627
Matthew Groves Avatar asked Feb 13 '26 17:02

Matthew Groves


1 Answers

Make sure to specify the header:

Content-Type: application/json

then the following body should work for your code:

{
    "Name": "myUserName",
    "Balance": 123.0,
    "ShoeSize": 30
}
like image 140
Mikhail Shilkov Avatar answered Feb 16 '26 07:02

Mikhail Shilkov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!