MVC - 如何在模型属性中使用连字符

时间:2014-07-30 09:36:14

标签: asp.net-mvc

我从某些服务器获得json响应,格式如下:

[
    {
        "email":"john.doe@sendgrid.com",
        "sg_event_id":"VzcPxPv7SdWvUugt-xKymw",
        "sg_message_id":"142d9f3f351.7618.254f56.filter-147.22649.52A663508.0",
        "timestamp":"1386636112",
        "smtp-id":"<142d9f3f351.7618.254f56@sendgrid.com>",
        "event":"processed",
        "category":"category1",
        "id": "001",
        "purchase": "PO1452297845",
        "Segmentid": "123456"
    },
    {
        "email":"not an email address",
        "smtp-id":"<4FB29F5D.5080404@sendgrid.com>",
        "timestamp":"1386636115",
        "reason":"Invalid",
        "event":"dropped",
        "category":"category2",
        "id":"001",
        "purchase":"PO1452297845",
        "Segmentid":"123456"
    },
    {
        "email":"john.doe@sendgrid.com",
        "sg_event_id":"vZL1Dhx34srS-HkO-gTXBLg",
        "sg_message_id":"142d9f3f351.7618.254f56.filter-147.22649.52A663508.0",
        "timestamp":"1386636113",
        "smtp-id":"<142d9f3f351.7618.254f56@sendgrid.com>",
        "event":"delivered",
        "category":"category1",
        "id": "001",
        "ip": "174.56.33.234",
        "url": "http://www.google.com/",
        "purchase": "PO1452297845",
        "Segmentid":"123456"
    }]

在mvc控制器操作中,我通过以下模型获得这些响应:

[ValidateInput(false)]
        [HttpPost]
        public async Task<ActionResult> Index(ResponseModel[] rec)
        {
        }

我的模特就像:

public class ResponseModel
{
    public int ReportId { get; set; }
    public string raw { get; set; }
    public int event_post_timestamp { get; set; }
    public string SegmentId { get; set; }
    public string url { get; set; }
    public string type { get; set; }
    public string status { get; set; }
    public string attempt { get; set; }
    public string useragent { get; set; }
    public string ip { get; set; }
    public string reason { get; set; }
    public string response { get; set; }
    public string newsletter { get; set; }
    public string category { get; set; }
    public string sg_message_id { get; set; }
    public string sg_event_id { get; set; }
    [Column("smtp-id")]
    [DataMember(Name="smtp-id")]
    [JsonProperty("smtp-id")]
    public string smtp_id { get; set; }
    public string email { get; set; }
    [Column("event")]
    [JsonProperty("event")]
    [DataMember(Name = "event")]
    public string @event { get; set; }
    public int timestamp { get; set; }
}

在行动中,我将初始化所有属性,但不是smtp-id。所以请建议我如何映射响应&#34; smtp-id&#34;属于我的模型。

2 个答案:

答案 0 :(得分:0)

创建与here

类似的ActionFilterAttribute

答案 1 :(得分:0)

我知道这是一篇非常古老的文章,但是我偶然发现了这件事,发现需要做两件事。

  1. [JsonProperty(PropertyName =“ message-id”)]使用Newtonsoft.Json和
  2. 一个简单的“自定义”模型活页夹https://stackoverflow.com/a/34030497/2455159

然后,可以将任何Json数据对象绑定到控制器中的模型/视图模型,该控制器接受诸如Webhook之类的已发布数据,该数据在属性名称/属性中具有无效(至少为'-')字符。