来自json的webapi 2绑定模型(webapi 2 bind model from json)
我需要从请求绑定模型并转换为我的自定义对象,我的请求数据是json,方法是post。
这是我在web api中的方法:
public IHttpActionResult Edit([ModelBinder(typeof(KModelBinder))] object data)我的问题是:我无法从modelbinder中的ValueProvider访问json。
public class KModelBinder : IModelBinder { public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext) { var valueProvider = bindingContext.ValueProvider; var valProviderResult = valueProvider.GetValue("id"); // .... } }请帮帮我
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"); // .... } }最满意答案
您可以尝试这样的基本控制器类
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*/ }之后你可以像这样定义你的控制器
public class UserController: BaseController<User> { //here you can override the base controller methods }我在当前的项目中使用了一些类似的方法并且工作正常。
检查一下,看看这是否适用于您的项目。
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.
更多推荐
发布评论