如何在点网核心中删除输入模型中的多余空间? [英] How to remove extra spaces in input model in dot net core?

查看:85
本文介绍了如何在点网核心中删除输入模型中的多余空间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我找到了一个链接,用于删除模型属性中字符串类型为

I have found a link to remove extra spaces in the model properties which is string type How to trim spaces of model in ASP.NET MVC Web API

如何在dot net core 2.1 Web API中实现相同的功能?

How to achieve the same functionality in dot net core 2.1 web api?

或者在dotnet核心中有可用的格式化程序来消除输入和输出模型中的多余空间吗?

Or is there any build in formatters available in dotnet core for removing extra spaces in input and output model?

先谢谢了吗?

推荐答案

我相信您链接的答案可能是您的最佳选择. 因此,请根据anwser创建一个转换器.

I believe the answer you linked is probably your best option. So create a converter as per the anwser.

class TrimmingConverter : JsonConverter
{
  public override bool CanConvert(Type objectType)
  {
    return objectType == typeof(string);
  }

  public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
  {
    if (reader.TokenType == JsonToken.String)
      if (reader.Value != null)
        return (reader.Value as string).Trim();

    return reader.Value;
  }

  public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
  {
    var text = (string)value;
    if (text == null)
      writer.WriteNull();
    else
      writer.WriteValue(text.Trim());
  }
}

,然后将其注册到Startup类中的ConfigureServices方法中,如下所示:

And then register it in your ConfigureServices method in your Startup class like so:

public void ConfigureServices(IServiceCollection services)
{
  services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
    .AddJsonOptions(a => a.SerializerSettings.Converters.Add(new TrimmingConverter()));
}

这篇关于如何在点网核心中删除输入模型中的多余空间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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