Querystring Model Binding ASP.NET WebApi

纵然是瞬间 提交于 2019-12-05 16:47:29

Implementing the IModelBinder,

public class DogModelBinder : IModelBinder
{
    public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
    {
        if (bindingContext.ModelType != typeof(Dog))
        {
            return false;
        }

        var model = (Dog)bindingContext.Model ?? new Dog();


        var hasPrefix = bindingContext.ValueProvider.ContainsPrefix(bindingContext.ModelName);

        var searchPrefix = (hasPrefix) ? bindingContext.ModelName + "." : "";

        model.NickName = GetValue(bindingContext, searchPrefix, "nick_name");

        int colorId = 0;
        if (int.TryParse(GetValue(bindingContext, searchPrefix, "colour"), out colorId))
        {
            model.Color = colorId; // <1>
        }

        bindingContext.Model = model;

        return true;
    }

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

And Create ModelBinderProvider,

public class DogModelBinderProvider : ModelBinderProvider
{
    private CollectionModelBinderProvider originalProvider = null;

    public DogModelBinderProvider(CollectionModelBinderProvider originalProvider)
    {
        this.originalProvider = originalProvider;
    }

    public override IModelBinder GetBinder(HttpConfiguration configuration, Type modelType)
    {
        // get the default implementation of provider for handling collections
        IModelBinder originalBinder = originalProvider.GetBinder(configuration, modelType);

        if (originalBinder != null)
        {
            return new DogModelBinder();
        }

        return null;
    }
}

and using in controller something like,

public IEnumerable<string> Get([ModelBinder(typeof(DogModelBinder))] Dog dog)
{
    //controller logic
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!