2013-03-18 72 views
4

我一直在尝试使用模型绑定来使我们的API更易于使用。当使用API​​时,只有在查询中包含数据时,才能将模型绑定绑定到数据。如何在从身体绑定时自定义模型绑定器?

我的代码是:

public class FunkyModelBinder : IModelBinder 
{ 
    public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext) 
    { 
     var model = (Funky) bindingContext.Model ?? new Funky(); 

     var hasPrefix = bindingContext.ValueProvider 
             .ContainsPrefix(bindingContext.ModelName); 
     var searchPrefix = (hasPrefix) ? bindingContext.ModelName + "." : ""; 
     model.Funk = GetValue(bindingContext, searchPrefix, "Funk"); 
     bindingContext.Model = model; 
     return true; 
    } 

    private string GetValue(ModelBindingContext context, string prefix, string key) 
    { 
     var result = context.ValueProvider.GetValue(prefix + key); 
     return result == null ? null : result.AttemptedValue; 
    } 
} 

当在ValueProvider财产上的bindingContext我只看到QueryStringValueProviderRouteDataValueProvider我认为这意味着,如果数据是在身体,我不会把它看。我应该怎么做?我想支持发布数据为json或者form-encoded。

+0

你能描述更多关于您的情况?在webapi中,默认情况下,来自正文的数据通过格式化程序绑定。 – 2013-03-19 06:16:12

+0

那么也许我应该使用格式化程序呢? – 2013-03-19 10:11:57

+0

是的..正确...看看下面的文章了解更多详情:http://blogs.msdn.com/b/jmstall/archive/2012/04/16/how-webapi-does-parameter-binding的.aspx – 2013-03-19 14:28:14

回答

0

我正在研究这一点。

WebApis Model Binder附带两个内置的ValueProviders。

QueryStringValueProviderFactory & RouteDataValueProviderFactory中搜索哪个

,当你调用

context.ValueProvider.GetValue 

这个问题有如何从身体数据绑定一些代码。

how to pass the result model object out of System.Web.Http.ModelBinding.IModelBinder. BindModel?

你可以创建一个自定义ValueProvider要做到这一点为好,可能是一个更好的主意 - 这将搜索匹配关键字的值。上面的链接只是在模型联编程序中执行此操作,这会将ModelBinder限制为仅在本体中查看。

public class FormBodyValueProvider : IValueProvider 
{ 
    private string body; 

    public FormBodyValueProvider (HttpActionContext actionContext) 
    { 
     if (actionContext == null) { 
      throw new ArgumentNullException("actionContext"); 
     } 

     //List out all Form Body Values 
     body = actionContext.Request.Content.ReadAsStringAsync().Result; 
    } 

//实现接口,并使用代码读取体,并找到自己的价值符合重点 }