-
Notifications
You must be signed in to change notification settings - Fork 10.5k
Closed
Labels
✔️ Resolution: AnsweredResolved because the question asked by the original author has been answered.Resolved because the question asked by the original author has been answered.Status: Resolvedarea-networkingIncludes servers, yarp, json patch, bedrock, websockets, http client factory, and http abstractionsIncludes servers, yarp, json patch, bedrock, websockets, http client factory, and http abstractionsquestion
Milestone
Description
public static async Task WriteJsonResponseAsync(this HttpContext context, JsonOptions options, int statusCode, object jsonObject)
{
// Serialize using the settings provided
using MemoryStream stream = new MemoryStream();
await JsonSerializer.SerializeAsync(stream, jsonObject, typeof(SomeGenericType), options.JsonSerializerOptions);
ReadOnlyMemory<byte> readOnlyMemory = new ReadOnlyMemory<byte>(stream.ToArray());
// Set the status code
context.Response.StatusCode = statusCode;
// Set the content type
context.Response.ContentType = "application/json; charset=utf-8";
// Write the content
await context.Response.Body.WriteAsync(readOnlyMemory);
await context.Response.Body.FlushAsync();
}
Is the above the correct way to do it for UTF8 json content? The JsonOptions passed are the default ones used in an ASP.NET Core 3.1 application.
Alternatively, from IdentityServer's library, do we just do the following:
public static async Task WriteJsonAsync(this HttpResponse response, string json, string contentType = null)
{
response.ContentType = (contentType ?? "application/json; charset=UTF-8");
await response.WriteAsync(json);
await response.Body.FlushAsync();
}
I'm not sure which is the more correct way, and which yields the same performance as when ASP.NET Core itself does the heavy lifting (serialization).
How is it being done there? Is it using streams like here, or something else entirely? My goal is to do the same heavy-lifting ASP.NET Core 3.1 originally does for serialization of objects.
Thank you.
Metadata
Metadata
Assignees
Labels
✔️ Resolution: AnsweredResolved because the question asked by the original author has been answered.Resolved because the question asked by the original author has been answered.Status: Resolvedarea-networkingIncludes servers, yarp, json patch, bedrock, websockets, http client factory, and http abstractionsIncludes servers, yarp, json patch, bedrock, websockets, http client factory, and http abstractionsquestion