如何修改Model Binding名称以绑定SendGrid传入的smtp-id字段
解决SendGrid字段与.NET模型属性的绑定问题
当然可以实现啦!针对你遇到的SendGrid传入字段smtp-id和模型属性SmtpId不匹配的绑定问题,这里有几种简单又实用的解决方案:
方案1:使用序列化特性(首推)
ASP.NET Core的模型绑定处理JSON请求时,会依赖项目中的JSON序列化库,只要给模型属性加上对应特性,就能直接映射到目标字段:
如果你用的是Newtonsoft.Json(Json.NET,早期ASP.NET Core默认)
public class InputModel { [JsonProperty("smtp-id")] public string SmtpId { get; set; } }
如果你用的是System.Text.Json(ASP.NET Core 3.0+默认)
using System.Text.Json.Serialization; public class InputModel { [JsonPropertyName("smtp-id")] public string SmtpId { get; set; } }
这种方式零额外逻辑,加个特性就完成映射,是最省心的做法。
方案2:自定义ModelBinder(适合复杂场景)
如果因为特殊需求不能用序列化特性,也可以自定义绑定逻辑来处理:
- 先写一个自定义的ModelBinder类:
public class SmtpIdModelBinder : IModelBinder { public Task BindModelAsync(ModelBindingContext bindingContext) { if (bindingContext == null) { throw new ArgumentNullException(nameof(bindingContext)); } // 读取并解析请求体的JSON数据 var rawBody = new StreamReader(bindingContext.HttpContext.Request.Body).ReadToEnd(); var jsonObj = Newtonsoft.Json.Linq.JObject.Parse(rawBody); // 提取smtp-id字段的值 var smtpId = jsonObj["smtp-id"]?.ToString(); // 绑定到InputModel并返回结果 var model = new InputModel { SmtpId = smtpId }; bindingContext.Result = ModelBindingResult.Success(model); return Task.CompletedTask; } }
- 给你的InputModel标记使用这个Binder:
[ModelBinder(BinderType = typeof(SmtpIdModelBinder))] public class InputModel { public string SmtpId { get; set; } }
不过这种方式相对繁琐,只建议在需要特殊绑定逻辑的场景下使用。
注意事项
记得在Action方法里用[FromBody]特性来接收模型,这样模型绑定器才能正确解析请求体的JSON内容:
[HttpPost] public IActionResult ReceiveSendGridWebhook([FromBody] InputModel model) { // 这里处理你的业务逻辑 return Ok(); }
内容的提问来源于stack exchange,提问作者Greg Gum
相关产品推荐
相关产品推荐

