ASP.NET 核心操作响应中的控制 Guid 格式

Control Guid format in ASP.NET Core action's response

假设我的 ASP.NET 核心 (API) 操作 returns 一个带有此 属性 的对象:

[WhatGoesHere("N")]                  // ?
public Guid MyGuid { get; set; }

它将被序列化为ffd76e47-609f-42bc-b6b8-b66dedab5561

我希望它被序列化为 ffd76e47609f42bcb6b8b66dedab5561。在代码中是 myGuid.ToString("N").

有没有我可以用来控制格式的属性?

您可以实现自定义 JsonConverter see here。并配置您的 aspnet 核心应用程序以注册此 JsonConverter 以进行输出格式化。这样,每次您的应用程序将 Guid 序列化为 JSON 时,您都会按照自己的方式获得它:

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

您还可以选择一些特定的 类 来使用转换器而不是全部,方法是在其上使用此属性:

[JsonConverter(typeof(MyCustomConverter))]
public class MyClass
{
    public Guid MyGuid { get;set; }
}

对于像您这样的简单场景,最简单的方法是使用另一个 属性 使用 MyGuid.ToString("N") 格式化 MyGuid。其中 "N" 表示您只需要不带“-”的数字。请参阅 documentation

您可以将 [JsonIgnore] 添加到 MyGuid 并将 [JsonProperty("MyGuid")] 属性添加到另一个 属性:

public class MyClass
{
    [JsonIgnore]
    public Guid MyGuid { get;set; }

    [JsonProperty("MyGuid")]
    public string DisplayGuid => MyGuid.ToString("N");
}

有了上面的内容,MyGuid 属性 将被忽略。相反,DisplayGuid 属性 将返回名称 MyGuid 和值 ffd76e47609f42bcb6b8b66dedab5561

对于更复杂的场景,您当然可以使用 @r1verside 提到的自定义 JsonConverter 选项。希望对您有所帮助

根据@r1verside 的回答,我的实现如下:

using System;

namespace MyProject {

  public sealed class GuidConverter : JsonConverter<Guid> {

    public GuidConverter() { }

    public GuidConverter(string format) { _format = format; }

    private readonly string _format = "N";

    public override void WriteJson(JsonWriter writer, Guid value, JsonSerializer serializer) {
      writer.WriteValue(value.ToString(_format));
    }

    public override Guid ReadJson(JsonReader reader, Type objectType, Guid existingValue, bool hasExistingValue, JsonSerializer serializer) {
      string s = (string)reader.Value;
      return new Guid(s);
    }

  }
}

可以这样使用:

[JsonConverter(typeof(GuidConverter))]    // defaults to format of "N"
public Guid MyGuid { get; set; }

但格式可以被覆盖:

[JsonConverter(typeof(GuidConverter), "X")]
public Guid MyGuid { get; set; }