How to return a json string with content type json in net 6 and minimal api?

Viewed 3331

If I have a json string (eg. read from a file) and my api returns as string, Postman will treat the response as text

app.MapGet("/myapi", () =>
{
    var json = File.ReadAllText("file.json");
    return json;  
});

So how can I force the content type to application/json? (not using Newtonsoft please) I was able with that workaround, but seems ugly

app.MapGet("/myapi", () =>
{
    var json = File.ReadAllText("file.json");
    var jo = JsonSerializer.Deserialize<object>(json);
    return Results.Json(jo);
});

Thanks

1 Answers

Your "workaround" is the correct method to return Json from a minimal API. Please see the methods available in the Results class for a full list of available responses.

Results.Json() is the correct response to return Json. IMO, your second technique is not "ugly", but the correct way to read and deserialize Json. Don't worry about the performance of deserializing the Json to an object only to serialize it again - if it becomes a problem you can address it at that point. What if you need to modify the json before returning it? You'd need to deserialize it in that case anyway.

I would also add that ideally you'd deserialize into a defined class rather than object:

var jo = JsonSerializer.Deserialize<CustomClass>(json);

Workaround

However, you could use Results.Text() and specify the content-type:

return Results.Text(json, contentType: "application/json");

which produces the same result in Postman as:

return Results.Json(jo);
Related