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?

1 Answer 1

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);
Sign up to request clarification or add additional context in comments.

4 Comments

Simpler : Client.PostAsJsonAsync("sendmessage", kv);
@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. =)
Your answer is perfect because it's show explicitly the need to serialize to json. The comment is just to notice this helper method.
This is the modern API for doing that learn.microsoft.com/en-us/dotnet/api/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.