永远不会调用Web API 2自定义模型绑定器

时间:2014-02-07 23:55:00

标签: asp.net-web-api2

我正在使用WebAPI 2的最新版本。我遇到了问题,默认的ModelBinder没有正确显示发布的值。我确实验证了值正确地发回到服务器,我能够使用请求对象检索它。所以决定实现我自己的自定义Model Binder。现在我遇到问题,这个自定义活页夹永远不会被调用,只调用默认活页夹。我错过了什么?

WebAPI方法

  public IHttpActionResult PutOrg([ModelBinder(typeof(MyOrgModelBinder))] Org org)
{

}

自定义ModelBinder

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.ModelBinding;
using System.Web.Http.ValueProviders;

namespace SM4.Models
{

    public class MyOrgModelBinder : IModelBinder
    {
        public bool BindModel(HttpActionContext controllerContext,
                                ModelBindingContext bindingContext)
        {

            var org = new Org
             {
                 OrgCode_PK = request.Form.Get("OrgCode_PK"),
                 OrgHeadCode_FK = request.Form.Get("OrgHeadCode_FK"),
                 Code = request.Form.Get("Code"),
                 Name = "THIS is FROM BINDER",
                 Description = request.Form.Get("Description"),
                 Address1 = request.Form.Get("Address1"),
                 Address2 = request.Form.Get("Address2"),
                 CountryCode_FK = request.Form.Get("CountryCode_FK"),
                 StateCode_FK = request.Form.Get("StateCode_FK"),
                 CityCode_FK = request.Form.Get("CityCode_FK"),
                 ZIP = request.Form.Get("ZIP"),
                 RowStatusCode_FK = request.Form.Get("RowStatusCode_FK"),
                 EffectiveDate = DateTime.ParseExact(request.Form.Get("EffectiveDate"), "yyyy-MM-dd",
                                        System.Globalization.CultureInfo.InvariantCulture),
                 TerminationDate = DateTime.ParseExact(request.Form.Get("TerminationDate"), "yyyy-MM-dd",
                                        System.Globalization.CultureInfo.InvariantCulture),
             };

            bindingContext.Model = org;
            return true;
        }
    } 
}

0 个答案:

没有答案