【问题标题】:How to change Model Binding Name如何更改模型绑定名称
【发布时间】:2018-05-24 12:01:34
【问题描述】:

我有一个像这样的 InputModel:

public class InputModel{
     public string SmtpId{get;set;}
}

但我真正想要的是将 ModelBinder 绑定到 smtp-id,因为这就是数据从 SendGrid 到达的方式。

这可能吗?

这是发布的内容:

 {
    "email":"john.doe@sendgrid.com",
    "timestamp": 1337197600,
    "smtp-id":"<4FB4041F.6080505@sendgrid.com>",
    "sg_event_id":"sendgrid_internal_event_id",
    "sg_message_id":"sendgrid_internal_message_id",
    "event": "processed"
  },

【问题讨论】:

    标签: asp.net asp.net-core asp.net-core-2.0


    【解决方案1】:

    您可以使用JsonProperty 属性来装饰您的属性,如下所示:

    public class InputModel{
        [JsonProperty("first_name")]
        public string FirstName{get;set;}
    }
    

    它适用于序列化和反序列化。

    【讨论】:

    • 仅供参考:ASP.NET Core 利用 JSON.NET(Newtonsoft.Json 包)进行 JSON 序列化/反序列化。因此,对于任何与 JSON 相关的内容,您都可以查阅该文档。
    • 只是它似乎没有被 ModelBinder 使用,因为即使使用该属性,它仍然没有绑定到模型。
    • 你如何绑定你的InputModel?例如,如果您使用的是标准表单编码,则它不会是 JSON,因此此答案将不适用。
    • 更新问题以包含示例
    【解决方案2】:

    这里正在跟踪此问题:here

    看来这将在未来的版本中更新。与此同时,这是可行的:

    [ModelBinder(Name = "smtp-id")]

    【讨论】:

      【解决方案3】:

      ASP.NET Core 3.0 及更高版本默认使用 System.Text.Json 而不是 Newtonsoft.Json(又名 Json.NET),因此您应该使用 JsonPropertyName 属性:

      using System.Text.Json.Serialization;
      
      public class InputModel
      {
         [JsonPropertyName("smtp-id")]
         public string SmtpId { get; set; }
      }
      

      如果您仍想使用 Newtonsoft.Json,您必须:

      1. 安装 Microsoft.AspNetCore.Mvc.NewtonsoftJson 包
      dotnet add package Microsoft.AspNetCore.Mvc.NewtonsoftJson
      
      1. 将 Newtonsoft.Json 设置为 Startup.cs 中的默认输入/输出格式化程序
      public class Startup
      {
         ...
      
         public void ConfigureServices(IServiceCollection services)
         {
            services.AddControllers().AddNewtonsoftJson();
            ...
         }
      
         ...
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-12-23
        • 2012-06-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-07-20
        • 2013-09-17
        • 1970-01-01
        相关资源
        最近更新 更多