0

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.

1
  • Why is it important to use the same serializer? Any serializer should serialize the same object to the exact same json, unless options are specified or need to be specified. If you need some specific behavior (like changing case) you can just implement your own serializer to do this or use newtonsoft with options. Commented Nov 11, 2021 at 0:09

1 Answer 1

3

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.