简体   繁体   English

在ASP.NET Core动作的响应中控制Guid格式

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

Suppose my ASP.NET Core (API) action returns an object with this property: 假设我的ASP.NET Core(API)操作返回一个具有此属性的对象:

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

It will be serialized as ffd76e47-609f-42bc-b6b8-b66dedab5561 . 它将被序列化为ffd76e47-609f-42bc-b6b8-b66dedab5561

I want it to be serialized as ffd76e47609f42bcb6b8b66dedab5561 . 我希望它被序列化为ffd76e47609f42bcb6b8b66dedab5561 In code that would be myGuid.ToString("N") . 在代码中将是myGuid.ToString("N")

Is there an attribute I can use to control the formatting? 是否有可用于控制格式的属性?

You can implement a custom JsonConverter see here . 您可以在此处实现自定义JsonConverter。 And configure your aspnet core application to register this JsonConverter for output formatting. 并配置您的aspnet核心应用程序以注册此JsonConverter以进行输出格式化。 This way every time your application would serialize a Guid to JSON you'll get it the way you want it: 这样,每当您的应用程序将Guid序列化为JSON时,您将以您希望的方式获取它:

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

You can also choose some particular classes to use the converter instead of all of them, by using this attribute on top of it: 您还可以选择一些特定的类来使用转换器而不是所有类,通过在它上面使用此属性:

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

For a simple scenario like yours, the easiest way to do this is to have another property which formats the MyGuid by using MyGuid.ToString("N") . 对于像你这样的简单场景,最简单的方法是使用另一个属性,使用MyGuid.ToString("N")格式化MyGuid Where "N" means that you just need the digits without "-". 其中“N”表示您只需要没有“ - ”的数字。 Please see the documentation 请参阅文档

You can add [JsonIgnore] to the MyGuid and add [JsonProperty("MyGuid")] attribute to the other property: 您可以将[JsonIgnore]添加到MyGuid并将[JsonProperty("MyGuid")]属性添加到其他属性:

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

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

With the above in place, MyGuid property will be ignored. 有了上述内容, MyGuid属性将被忽略。 Instead, DisplayGuid property will be returned with the name MyGuid with the value ffd76e47609f42bcb6b8b66dedab5561 而是返回DisplayGuid属性,名称为MyGuid ,值为ffd76e47609f42bcb6b8b66dedab5561

For more complex scenarios, you can surely go for a custom JsonConverter option as mentioned by @r1verside. 对于更复杂的场景,您肯定可以使用@ r1verside提到的自定义JsonConverter选项。 I hope this helps 我希望这有帮助

Based on @r1verside's answer, here is my implementation: 基于@ 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);
    }

  }
}

It can be used like this: 它可以像这样使用:

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

but format can be overridden: 但格式可以被覆盖:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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