【问题标题】:How can I bind model in ASP.NET MVC CORE with special attributes如何在 ASP.NET MVC CORE 中使用特殊属性绑定模型
【发布时间】:2018-08-08 15:13:22
【问题描述】:

在我们的项目中,有一种代码风格迫使我们使用带有属性名称的模型,例如 camelcase-style

public class MyModelClass { 
   public int CountryId { get; set; } 
   public int CountryName { get; set; } 
}

但是调用 REST-API 的服务会使用以下参数传输 HTTP-body country_idcountry_name。而且我无法在控制器操作中将 http-query 映射到我的模型。是否有 ASP.NET CORE MVC 方式来映射这样的属性

public class MyModelClass { 
   [SpecialAttribute("country_id")]
   public int CountryId { get; set; } 

   [SpecialAttribute("country_name")]
   public int CountryName { get; set; } 
}

或者有其他方法可以实现吗?

【问题讨论】:

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


【解决方案1】:

使用 来序列化和反序列化 json。 You can view the documentation here。话虽如此,您只需使用JsonPropertyAttribute 即可轻松做您想做的事:

public class MyModelClass 
{ 
  [JsonProperty("country_id")]
  public int CountryId { get; set; } 

  [JsonProperty("country_name")]
  public int CountryName { get; set; } 
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-01-02
    • 1970-01-01
    • 2021-06-27
    • 2022-06-11
    • 2018-08-30
    • 1970-01-01
    • 1970-01-01
    • 2020-01-08
    相关资源
    最近更新 更多