ASP .NET Web API ModelBinder单个参数

编程入门 行业动态 更新时间:2024-10-25 08:27:49
本文介绍了ASP .NET Web API ModelBinder单个参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

当前,我有一个可以正常工作的ModelBinder:

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; } }

如您所见,我正在映射整个绑定上下文.Model,但我真正想做的是仅映射Model的Media字段,并默认映射所有其他字段。

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.

这是我的控制器:

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

这可以实现吗?

推荐答案

以下是我们所有模型联编程序的定义方式:

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

公共类FooBinder:IModelBinder {

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.

更多推荐

ASP .NET Web API ModelBinder单个参数

本文发布于:2023-10-29 07:49:33,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1539135.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:参数   NET   ASP   Web   ModelBinder

发布评论

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

>www.elefans.com

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