在ASP.NET Core MVC中自定义响应序列化 [英] Customizing response serialization in ASP.NET Core MVC

查看:176
本文介绍了在ASP.NET Core MVC中自定义响应序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在ASP.NET Core MVC中自定义类型序列化到响应的方式?

Is it possible to customize the way types are serialized to the response in ASP.NET Core MVC?

在我的特定用例中,我有一个结构AccountId,该结构只是环绕Guid:

In my particular use case I've got a struct, AccountId, that simply wraps around a Guid:

public readonly struct AccountId
{
    public Guid Value { get; }

    // ... 
}

毫不奇怪,当我从一个动作方法返回它时,它会序列化为以下内容:

When I return it from an action method, unsurprisingly, it serializes to the following:

{ "value": "F6556C1D-1E8A-4D25-AB06-E8E244067D04" }

相反,我想自动解包Value,以便将其序列化为纯字符串:

Instead, I'd like to automatically unwrap the Value so it serializes to a plain string:

"F6556C1D-1E8A-4D25-AB06-E8E244067D04"

可以配置MVC来实现吗?

Can MVC be configured to achieve this?

推荐答案

您可以使用在您的情况下,它看起来像这样:

In your case, it would look like this:

[JsonConverter(typeof(AccountIdConverter))]
public readonly struct AccountId
{
    public Guid Value { get; }

    // ... 
}

public class AccountIdConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
        => objectType == typeof(AccountId);

    // this converter is only used for serialization, not to deserialize
    public override bool CanRead => false;

    // implement this if you need to read the string representation to create an AccountId
    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        => throw new NotImplementedException();

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        if (!(value is AccountId accountId))
            throw new JsonSerializationException("Expected AccountId object value.");

        // custom response 
        writer.WriteValue(accountId.Value);
    }
}

如果您不想使用JsonConverter属性,则可以在ConfigureServices中添加转换器(需要Microsoft.AspNetCore.Mvc.Formatters.Json):

If you prefer not to use the JsonConverter attribute, it's possible to add converters in ConfigureServices (requires Microsoft.AspNetCore.Mvc.Formatters.Json):

public void ConfigureServices(IServiceCollection services)
{
    services
        .AddMvc()
        .AddJsonOptions(options => {
            options.SerializerSettings.Converters.Add(new AccountIdConverter());
        });
}

这篇关于在ASP.NET Core MVC中自定义响应序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆