简体   繁体   中英

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.

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 eg .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.


eg 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM