Querystring Model Binding ASP.NET WebApi

醉酒当歌 提交于 2019-12-07 10:10:52

问题


I have the following model

public class Dog
{
    public string NickName { get; set; }
    public int Color { get; set; }
}

and I have the following api controller method which is exposed through an API

public class DogController : ApiController
{
  // GET /v1/dogs
  public IEnumerable<string> Get([FromUri] Dog dog)
  { ...}

Now, I would like to issue the GET request as follows:

GET http://localhost:90000/v1/dogs?nick_name=Fido&color=1

Question: How do I bind the query string parameter nick_name to property NickName in the dog class? I know I can call the API without the underscore (i.e. nickname) or change NickName to Nick_Name and get the value, but I need the names to remain like that for convention.

Edit This question is not a duplicate because it is about ASP.NET WebApi not ASP.NET MVC 2


回答1:


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
}


来源:https://stackoverflow.com/questions/33247992/querystring-model-binding-asp-net-webapi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!