Search code examples
c#jsonasp.net-web-api2modelbinders

webapi 2 bind model from json


I need to bind model from request and convert to my custom object, my request data is json and method is post.

This is my method in web api:

public IHttpActionResult Edit([ModelBinder(typeof(KModelBinder))] object data) 

My problem is: I cannot access to json from ValueProvider in modelbinder.

public class KModelBinder : IModelBinder {
    public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext) {
        var valueProvider = bindingContext.ValueProvider;
        var valProviderResult = valueProvider.GetValue("id");
        // ....
    }
}

Solution

  • You can try a base controller class like this

    public class BaseController<T>: ApiController
    {
    
        //here you can add whatever dependency injection you may use
        public BaseController(DbContext context) 
        {
            _context = context;  
        }
    
       [HttpPost]
       public IHttpActionResult Add(T data)
       {
           return Ok(_context.Add(data));
       }
    
       [HttpPut]
       public IHttpActionResult Edit(T data)
       {
            _context.Modify(data); //here depends on your ORM or data access layer
            return Ok(data);
       }
    
       /*other methods you think are necessary in this base controller*/
    }
    

    Afterwards you can define your controllers like this

    public class UserController: BaseController<User>
    {
       //here you can override the base controller methods
    }
    

    I use somewhat similarly approach in my current project and works fine.

    Check it out and see if this works for your project.