Home > OS >  Post request to Minimal API service with JSON body
Post request to Minimal API service with JSON body

Time:01-20

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:

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?

CodePudding user response:

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);
  • Related