ASP .NET Web API ModelBinder single parameter

蓝咒 提交于 2019-12-11 15:42:54

问题


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:


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.



来源:https://stackoverflow.com/questions/52084903/asp-net-web-api-modelbinder-single-parameter

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