Home > Enterprise >  ASP.NET Core 6 - How to take JSON input via MapPost() without deserializing?
ASP.NET Core 6 - How to take JSON input via MapPost() without deserializing?

Time:12-29

I am new to C#, JSON and web programming in general, so please correct me if I show signs of misunderstanding on certain concepts.

On ASP.NET Core 6, I want to use MapPost() to take a JSON string without having to deserialize it. I have previously made a class and successfully deserialized inputs, but now I want to try plain string. This is how part of my Web API's Program.cs looks like:

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

Dictionary<string, string> mydictionary = new();

app.MapPost("/add_data/{queryKey}", (string queryKey, string jsonstring) =>
{
    mydictionary.Add(queryKey, jsonstring);
    return jsonstring;
});

An example of cURL API testing:

curl -X POST 'https://localhost:5001/add_data/my_first_entry' -d '{"name":"Sebastian", "age":35, "car":"Renault"}' -H 'Content-Type: application/json'

expected response:

'{"name":"Sebastian", "age":35, "car":"Renault"}'

Is it possible?

CodePudding user response:

Simply add [FromBody] attribute to body and it will work as expected.

app.MapPost("/add_data/{queryKey}", (string queryKey, [FromBody] string jsonstring) =>
{
    mydictionary.Add(queryKey, jsonstring);
    return jsonstring;
});

Request:

POST /add_data/qq HTTP/1.1
Content-Type: application/json
User-Agent: PostmanRuntime/7.28.4
Accept: */*
Cache-Control: no-cache
Host: localhost:7297
Accept-Encoding: gzip, deflate, br
Connection: keep-alive
Content-Length: 21
 
"{ data = \"hello\"}"

enter image description here


UPDATE:

Right solution for raw requests:

app.MapPost("/add_data/{queryKey}", async delegate(HttpContext context)
{
    using (StreamReader reader = new StreamReader(context.Request.Body, Encoding.UTF8))
    {
        string queryKey = context.Request.RouteValues["queryKey"].ToString();
        string jsonstring = await reader.ReadToEndAsync();
        mydictionary.Add(queryKey, jsonstring);
        return jsonstring;
    }
});
  • Related