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

2

12

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

Sparling answered 31/1, 2022 at 8:29 Comment(0)
G
16

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);
Gryphon answered 9/2, 2022 at 12:19 Comment(3)
Results.Json encodes the string again, so if "jo" is already a json-encoded string the output may not be what one expects. Results.Text does not alter the string value.Teide
If you use NewtonsoftJson like this : JsonConvert.SerializeObject(someObject) then you need to use Result.Text(json, "application/json"). Otherwise the json will be encoded again from Result.Json(..) and it will not be right like mentioned in the previous commentGendron
Thanks for Results.Text()!!!Someplace
E
5

The correct answer is:

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

The answer by @haldo is incorrect because he states that this is a workaround, which is not. You already have JSON and you want to output the same JSON without alterations, and you simply want to tell browsers that this is JSON. So no workaround here, just the correct way of outputting JSON content.

Efficiency answered 5/12, 2022 at 16:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.