Skip to content

[Question] Proper way of writing a JSON response in middleware using HttpContext.Response? #19891

@kikaragyozov

Description

@kikaragyozov
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

No one assigned

    Labels

    ✔️ Resolution: AnsweredResolved 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 abstractionsquestion

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions