Web API中基类的自定义模型绑定器



给定以下型号

public class RequestBase
{
    public DateTime TransactionTimestamp { get; set; }
    public Guid RequestMessageId { get; set; }
}
 [ModelBinder(typeof(RequestBaseModelBinder))]
public class StandardRequest : RequestBase
{
     public Guid MyGuidId { get; set; }
    public int MyIntId { get; set; }
}

RequestBase中的值是通过头发送的,所以我试图实现一个自定义的模型绑定器,将它们绑定到模型

这就是我到目前为止得到的

 public class RequestBaseModelBinder :IModelBinder
{
    public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
    {
        var requestBase = bindingContext.Model as RequestBase;
        if (requestBase != null)
        {
            requestBase.RequestMessageId =
               Guid.Parse(actionContext.Request.Headers.GetValues("RequestMessageId").FirstOrDefault());
            requestBase.TransactionTimestamp =
               DateTime.Parse(actionContext.Request.Headers.GetValues("TransactionTimestamp").FirstOrDefault());
            return true;
        }
        return false;
    }
}

它目前不工作,因为bindingContext.Model为空

否,bindingContext.Model是您将从操作参数中获得的对象。

您应该从actionContext.Request获取头部,构建模型,并将模型设置为bindingContext.model

代码应该像:

Dictionary<string, string> kvps = new Dictionary<string, string>();
        if (!string.IsNullOrEmpty(actionContext.Request.RequestUri.Query))
        {
            kvps = actionContext.Request.GetQueryNameValuePairs().ToDictionary(a=>a.Key,a=>a.Value);
        }
        //Check and get source data from body 
        else if (actionContext.Request.Content.IsFormData())
        {
            var bodyString = actionContext.Request.Content.ReadAsStringAsync().Result;
            try
            {
                kvps = ConvertToKvps(bodyString);
            }
            catch (Exception ex)
            {
                bindingContext.ModelState.AddModelError(bindingContext.ModelName, ex.Message);
                return false;
            }
        }
        else
        {
            bindingContext.ModelState.AddModelError(bindingContext.ModelName, "No input data");
            return false;
        }
        Object obj = null;
        try
        {
            obj = new Something(kvps);//build your object by key value pairs
        }
        catch (Exception ex)
        {
            bindingContext.ModelState.AddModelError(
                bindingContext.ModelName, ex.Message);
            return false;
        }
        bindingContext.Model = obj;
        return true;

请参见此示例:http://www.codeproject.com/Articles/701182/A-Custom-Model-Binder-for-Passing-Complex-Objects

相关内容

  • 没有找到相关文章

最新更新