【问题标题】:Customizing response serialization in ASP.NET Core MVC在 ASP.NET Core MVC 中自定义响应序列化
【发布时间】:2018-03-08 17:26:29
【问题描述】:

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

在我的特定用例中,我有一个结构 AccountId,它简单地包裹在 Guid 周围:

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

    // ... 
}

当我从动作方法返回它时,不出所料,它会序列化为以下内容:

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

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

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

可以配置 MVC 来实现这一点吗?

【问题讨论】:

  • 我认为您最好的选择是自定义JsonConverter。 JSON.NET 被用作默认的 JSON 序列化程序,因此请查阅他们的文档。
  • 从阅读custom-formatters开始
  • @ChrisPratt 这似乎是要走的路。我认为有一些更通用的东西(如果我想返回 XML 而不是 JSON,我必须配置另一个格式化程序),但它就足够了。
  • 您可以尝试在您的结构上覆盖ToString。不过,这不仅会影响序列化。
  • 我已经尝试过了,但 JSON.NET 似乎忽略了它。我现在将使用自定义 JsonConverter,也许会在 MVC 问题跟踪器上提出更通用的解决方案。

标签: c# asp.net-core asp.net-core-mvc


【解决方案1】:

您可以使用 custom converter 自定义 JSON.NET 生成的输出。

在你的情况下,它看起来像这样:

[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):

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

【讨论】:

  • 这几乎就是我最终这样做的方式。我只是不喜欢JsonConverter 属性,所以我将我的转换器添加到SerializerSettings.Converters 中的ConfigureServices'AddMvc
  • 为了完整起见,我已将您的替代方案添加到我的答案中。
  • 这也适用于 AddControllersWithViews,这是在 Visual Studio 2019 的 React.js 模板中使用的。 services.AddControllersWithViews() .AddJsonOptions(options => { options.JsonSerializerOptions.Converters.Add (new MyAwesomeConverter()); });
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-12
  • 1970-01-01
  • 1970-01-01
  • 2019-03-10
相关资源
最近更新 更多