WebAPI post action复杂类型Parameter不调用自定义MediaTypeFormatter并保持为null

时间:2014-03-18 13:32:37

标签: jquery json post asp.net-web-api mediatypeformatter

我正在尝试将数据从jquery发布到ASP.Net WebAPI post方法以保存它。

这是我发送请求的jquery方法

'saveAbsenceRecord': function (absenceRecord) {
        var url = helper.apiPath + 'absence';
        $.ajax({
            url: url,
            type: 'POST',
            data: JSON.stringify(absenceRecord) ,
            contentType: 'application/json; charset=utf-8',
            async: false,
            success: function (data) {
                return data;
            },
            error: function (x, y, z) {
                alert(x + '\n' + y + '\n' + z);
            }
        });
};

以下是我从请求中捕获的json

"{\"AbsenceDate\":\"11 March 2014\",\"IsHalfDay\":false,\"DateModified\":\"18 March 2014\",\"User\":{\"Id\":2,\"Name\":\"\",\"EmpId\":\"\",\"LanId\":\"\",\"EmailId\":\"\",\"Permissions\":[]},\"ModifiedBy\":{\"Id\":2,\"Name\":\"\",\"EmpId\":\"\",\"LanId\":\"\",\"EmailId\":\"\",\"Permissions\":[]},\"Type\":{\"Id\":4,\"Reason\":\"Unplanned\"},\"Description\":\"Test\"}"

这是我的WebAPI帖子方法

// POST api/absence
        public HttpResponseMessage Post([FromBody]AbsenceRecord absenceRecord)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    Store store = new Store();
                    var result = store.UpdateAbsenceRecord(absenceRecord);
                    return Request.CreateResponse(HttpStatusCode.OK, result);
                }
                else
                {
                    return Request.CreateResponse(HttpStatusCode.InternalServerError, "Invalid model state");
                }
            }
            catch (Exception ex)
            {
                return Request.CreateResponse(HttpStatusCode.InternalServerError, ex.Message);
            }
        }

以下是我的参数类型

 public class User : IEntity
    {
        public int Id { get; set; }
        [MaxLength(10)]
        public string EmpId { get; set; }
        [MaxLength(50)]
        public string UserName { get; set; }
        public virtual List<UserPermission> Permissions { get; set; }
        public string EmailId { get; set; }
        public string LanId { get; set; }
    }
public class AbsenceType : IEntity
    {
        public int Id { get; set; }
        [MaxLength(50)]
        public string Reason { get; set; }
        [MaxLength(10)]
        public string ColorHash { get; set; }
    }
    public class AbsenceRecord : IEntity
    {
        public int Id { get; set; }
        public DateTime AbsenceDate { get; set; }
        public virtual AbsenceType Type { get; set; }
        public bool IsHalfDay { get; set; }
        public DateTime DateModified { get; set; }
        public string Description { get; set; }
        public virtual User User { get; set; }
        public virtual User ModifiedBy { get; set; }
    } 

我怀疑我的Json与参数类型的结构不匹配。所以我需要eiter模型绑定器或MediaType Formatter。由于我想在体内发送数据,我不会选择Binder。

我尝试过编写媒体类型格式化程序并将其注册为

public class AbsenceRecordFormatter : MediaTypeFormatter
    {
        public AbsenceRecordFormatter()
        {
            SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/json"));   
        }
        public override bool CanReadType(Type type)
        {
            return type == typeof(AbsenceRecord);
        }
        public override bool CanWriteType(Type type)
        {
            return type == typeof(AbsenceRecord);
        }

        public override System.Threading.Tasks.Task WriteToStreamAsync(Type type, object value, System.IO.Stream writeStream, System.Net.Http.HttpContent content, System.Net.TransportContext transportContext)
        {                
            return base.WriteToStreamAsync(type, value, writeStream, content, transportContext);
        }
    }


config.Formatters.Add(new AbsenceRecordFormatter());

但调用此方法时不会调用该代码。 任何机构都可以建议为什么不调用格式化程序吗?

1 个答案:

答案 0 :(得分:0)

按顺序评估全局configuration.Formatters集合。因此,将在格式化程序之前选择默认的JSON格式化程序。从格式化程序集合中删除JSON,或者在开头插入格式化程序。

 config.Formatters.Insert(0,new AbsenceRecordFormatter());