来自json的webapi 2绑定模型(webapi 2 bind model from json)

编程入门 行业动态 更新时间:2024-10-21 04:09:16
来自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.

更多推荐

本文发布于:2023-08-02 18:43:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1379583.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:绑定   模型   webapi   json   bind

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!