Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Post request to Minimal API service with JSON body

I’ve got a minimal API service with a MapPost:

app.MapPost("/sendmessage", (RabbitMessage rm) => server.SendMessage(rm.exchange, 
rm.routingkey, rm.message));

app.Run();

record RabbitMessage(string exchange, string routingkey, string message);

It works fine when sending a JSON with Postman:

{
    "message": "msg",
    "routingkey": "freestorage",
    "exchange": "system"
}

But from a C# client:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

var kv = new Dictionary<string, string> {
    { "exchange", "system" },
    { "routingkey", routingkey },
    { "message", message }
};

var content = new FormUrlEncodedContent(kv);

string contentType = "application/json";

if (Client.DefaultRequestHeaders.Accept.FirstOrDefault(hdr => hdr.MediaType == contentType) == default)
    Client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(contentType));


var response = await Client.PostAsync("sendmessage", content);

The response is UnsupportedMediaType. What is the proper way to send these values to minimal API? Or do I need to setup the API itself differently?

>Solution :

I don’t think using FormUrlEncodedContent is the correct way as it is used for application/x-www-form-urlencoded MIME type.

Instead, you should pass the request body with StringContent and serialize the kv as content.

using System.Text;
using Newtonsoft.Json;

var stringContent = new StringContent(JsonConvert.SerializeObject(kv), 
    Encoding.UTF8, 
    "application/json");

var response = await Client.PostAsync("sendmessage", stringContent);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading