Asp.net 从主体绑定时,如何创建自定义modelbinder?

Asp.net 从主体绑定时,如何创建自定义modelbinder?,asp.net,asp.net-web-api,Asp.net,Asp.net Web Api,我一直在尝试使用模型绑定,以使我们的API更易于使用。当使用API时,当数据在主体中时,我无法获得要绑定的模型绑定,只有当它是查询的一部分时 我的密码是: public class FunkyModelBinder : IModelBinder { public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext) { var model = (Fun

我一直在尝试使用模型绑定,以使我们的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;
    }
}

查看
bindingContext
上的
ValueProvider
属性时,我只看到
QueryStringValueProvider
RouteDataValueProvider
,我认为这意味着如果数据在正文中,我将无法获取它。我该怎么做?我想支持将数据发布为json或表单编码

我也在调查此事

WebAPI模型绑定器附带两个内置的ValueProvider

QueryStringValueProviderFactory和RoutedDataValueProviderFactory

当你打电话的时候会被搜索

context.ValueProvider.GetValue
这个问题有一些关于如何从主体绑定数据的代码

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
}

您也可以创建一个定制的ValueProvider来实现这一点,这可能是一个更好的主意——搜索与键匹配的值。上面的链接仅在model binder中执行此操作,这将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
}

你能详细描述一下你的情况吗?在webapi中,默认情况下,来自主体的数据是通过格式化程序绑定的。因此,也许我应该为此使用格式化程序?是的..对…查看以下文章以了解更多详细信息: