Johannes Hoff
Johannes Hoff

Reputation: 3901

Use serializer within ASP.NET Core MVC controller?

ASP.NET Core MVC serializes responses returned from my Microsoft.AspNetCore.Mvc.ControllerBase controller methods.

So the following will serialize a MyDTO object to JSON:

[Produces("application/json")]
[HttpGet]
public MyDTO test() 
{
    return new MyDTO();
}

However, I want to use the exact same serializer within the method itself. Is that possible? Something like

[Produces("application/json")]
[HttpGet]
public MyDTO test() 
{
    var result = new MyDTO();
    string serialized = this.<SOMETHING GOES HERE>(result);
    Console.WriteLine($"I'm about to return {serialized}");
    return result;
}

It's important that it's the same serializer, including any options set in the stack.

Upvotes: 0

Views: 1979

Answers (1)

Matthias
Matthias

Reputation: 1437

Don't think that's possible because it's hidden away within IActionResultExecutor<JsonResult>. Default will be the SystemTextJsonResultExecutor but could be overwritten on startup when using e.g. .AddNewtonsoftJson(...)...

You could set the Json Format Options explicitly in startup.cs and then just use the same options wherever else you need to serialize. That way all serializations will be done exactly the same way.


e.g. If you are using JsonSerializer:

public static class JsonSerializerExtensions
{
    public static JsonOptions ConfigureJsonOptions(this JsonOptions options)
    {
        // your configuration
        options.JsonSerializerOptions.NumberHandling = JsonNumberHandling.WriteAsString;
        return options;
    }
}

startup.cs

services
    .AddControllers()
    .AddJsonOptions(options => options.ConfigureJsonOptions());

Conroller.cs

string serialized =JsonSerializer.Serialize(new MyDTO(), options: new JsonOptions().ConfigureJsonOptions().JsonSerializerOptions);

Upvotes: 3

Related Questions