从身体绑定时如何做自定义模型绑定器?

Tom*_*son 6 asp.net asp.net-web-api

我一直在尝试使用模型绑定来使我们的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;
    }
}
Run Code Online (Sandbox Code Playgroud)

当在寻找ValueProvider的财产bindingContext我只看到QueryStringValueProviderRouteDataValueProvider我认为的手段,如果数据是在身体,我不会得到它。我应该怎么做?我想支持以json或表单编码形式发布数据。

War*_*rth 4

我也在研究这个问题。

WebApis Model Binder 附带两个内置 ValueProvider。

QueryStringValueProviderFactory 和 RouteDataValueProviderFactory

您拨打电话时会搜索到哪些内容

context.ValueProvider.GetValue
Run Code Online (Sandbox Code Playgroud)

这个问题有一些关于如何从正文绑定数据的代码。

如何从 System.Web.Http.ModelBinding.IModelBinder 传递结果模型对象。绑定模型?

您也可以创建一个自定义 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;
    }

    // Implement Interface and use code to read the body
    // and find your Value matching your Key
}
Run Code Online (Sandbox Code Playgroud)