Trying to replicate a Framework API using .NET Core 6 and minimal APIs.
One thing is I am getting "application/json" as the content-type if I return Results.Ok(data)
.
Yes it should be json, but this is replicating legacy functionality.
I can get the results to be text/plain if I just use return data;
.
But would like to use Results
if I can.
Setting this does not work:
context.Response.ContentType = "text/plain";
return Results.Ok(data);
Still comes back application/json
.
Any suggestions?
CodePudding user response:
You can specify a custom IResult
type for text/plain
class PlainTextResult : IResult
{
private readonly string _text;
public PlainTextResult(string text)
{
_text = text;
}
public Task ExecuteAsync(HttpContext httpContext)
{
httpContext.Response.StatusCode = 200;
httpContext.Response.ContentType = MediaTypeNames.Text.Plain;
httpContext.Response.ContentLength = Encoding.UTF8.GetByteCount(_text);
return httpContext.Response.WriteAsync(_text);
}
}
Then you just return that in your MapGet like so
app.MapGet("/text", () => new PlainTextResult("This is plain text"));
As a side note, there is also the result type of Text
that takes a content type parameter
return Results.Text("This is plain text", "text/plain", Encoding.UTF8);
CodePudding user response:
Sounds like you want to use Results.Json
:
Results.Json(data, contentType:"text/plain");