Request Model Binding with ASP.NET WebApi Binding

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 that opens via API

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

Now I would like to send a GET request as follows:

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

Question: How to associate the nick_name query string parameter with the NickName property in the dog class? I know that I can name the API without an underscore (like a nickname) or change NickName to Nick_Name and get the value, but I need the names to stay the same for convention.

Edit This question is not duplicated because it is about ASP.NET WebApi, not ASP.NET MVC 2

+4
source share
1 answer

Implementation 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;
    }
}

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;
    }
}

-

public IEnumerable<string> Get([ModelBinder(typeof(DogModelBinder))] Dog dog)
{
    //controller logic
}
+3

Source: https://habr.com/ru/post/1612506/


All Articles