ASP .NET Web API ModelBinder single parameter

2019-08-23 05:04发布

Currently I've got this ModelBinder that works just fine:

public class FooModelBinder : IModelBinder
    {
        public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
        {
            var body = JObject.Parse(actionContext.Request.Content.ReadAsStringAsync().Result);
            IEnumerable<Foo1> media = new List<Foo1>();
            var transaction = body.ToObject<Foo2>();

            media = body["Media"].ToObject<List<Foo3>>();


            transaction.Media = media;
            bindingContext.Model = transaction;

            return true;
        }
    }

As you can see I'm mapping the whole bindingContext.Model, but what I really want to do is to map just the Media field of the Model and all of the other fields to map as default.

This is my controller:

public HttpResponseMessage Post([ModelBinder(typeof(FooModelBinder))] Foo request)
        {
            //do something
        }

Is this achievable?

1条回答
Viruses.
2楼-- · 2019-08-23 05:43

Here's how all of our model binders are defined:

public class FooBinder : IModelBinder {

public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
{
    if (bindingContext.ModelType == typeof(Foo))
    {
        return FooParameter(actionContext, bindingContext);
    }

    return false;
}

If you want to make multiple parameters from your input you can just specify your desired binder in the your controller method.

    public async Task<HttpResponseMessage> GetFoo(
        [ModelBinder] Foo1 foo1 = null, [ModelBinder] Foo2 foo2 = null)
    {
       ... 
    }

I may have misunderstood your question but this is an example of real code in our system.

查看更多
登录 后发表回答