1

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?

Yong Shun
  • 35,286
  • 4
  • 24
  • 46
Serve Laurijssen
  • 9,266
  • 5
  • 45
  • 98

1 Answers1

3

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);
Yong Shun
  • 35,286
  • 4
  • 24
  • 46
  • 1
    Simpler : `Client.PostAsJsonAsync("sendmessage", kv);` – vernou Jan 20 '23 at 09:25
  • @vernou, yeah, I think you can write it as an answer post. This will help the post owner and future readers and at the same time gain the reputation points for you. =) – Yong Shun Jan 20 '23 at 09:28
  • Your answer is perfect because it's show explicitly the need to serialize to json. The comment is just to notice this helper method. – vernou Jan 20 '23 at 09:33
  • 1
    This is the modern API for doing that https://learn.microsoft.com/en-us/dotnet/api/system.net.http.json.httpclientjsonextensions.postasjsonasync?view=net-7.0 – davidfowl Jan 23 '23 at 03:42