https://docs.microsoft.com/en-us/aspnet/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api

没有特殊需求的话,默认的绑定就可以使用。比如request body是json字符串。然后只要对应的class的属性和json能够对应上就可以了。

The media type determines how Web API serializes and deserializes the HTTP message bodyWeb API has built-in support for XML, JSON, BSON, and form-urlencoded data, and you can support additional media types by writing a media formatter.

When Web API calls a method on a controller, it must set values for the parameters, a process called binding. This article describes how Web API binds parameters, and how you can customize the binding process.

By default, Web API uses the following rules to bind parameters:

  • If the parameter is a "simple" type, Web API tries to get the value from the URI. Simple types include the .NET primitive types(int, bool, double, and so forth), plus TimeSpan, DateTime, Guid, decimal, and string, plus any type with a type converter that can convert from a string. (More about type converters later.)
  • For complex types, Web API tries to read the value from the message body, using a media-type formatter.

For example, here is a typical Web API controller method:

HttpResponseMessage Put(int id, Product item) { ... }

The id parameter is a "simple" type, so Web API tries to get the value from the request URI.

The item parameter is a complex type, so Web API uses a media-type formatter to read the value from the request body.

To get a value from the URI, Web API looks in the route data and the URI query string.

The route data is populated when the routing system parses the URI and matches it to a route.

For more information, see Routing and Action Selection.

In the rest of this article, I'll show how you can customize the model binding process.

For complex types, however, consider using media-type formatters whenever possible.

A key principle of HTTP is that resources are sent in the message body, using content negotiation to specify the representation of the resource.

Media-type formatters were designed for exactly this purpose.

Using [FromUri]

Using [FromBody]

To force Web API to read a simple type from the request body, add the [FromBody] attribute to the parameter:

public HttpResponseMessage Post([FromBody] string name) { ... }

In this example, Web API will use a media-type formatter to read the value of name from the request body. Here is an example client request.

POST http://localhost:5076/api/values HTTP/1.1
User-Agent: Fiddler
Host: localhost:5076
Content-Type: application/json
Content-Length: 7
"Alice"

When a parameter has [FromBody], Web API uses the Content-Type header to select a formatter. In this example, the content type is "application/json" and the request body is a raw JSON string (not a JSON object).

At most one parameter is allowed to read from the message body. So this will not work:

// Caution: Will not work!
public HttpResponseMessage Post([FromBody] int id, [FromBody] string name) { ... }

The reason for this rule is that the request body might be stored in a non-buffered stream that can only be read once.

Type Converters

Model Binders

A more flexible option than a type converter is to create a custom model binder. With a model binder, you have access to things like the HTTP request, the action description, and the raw values from the route data.

To create a model binder, implement the IModelBinder interface. This interface defines a single method, BindModel:

bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext);

这个接口目前只能通过https://www.nuget.org/packages/Microsoft.AspNet.WebApi.Core/来获得

 

As for VS2017 - as said in the asp.net forums Microsoft has moved the namespace to a Nuget package called Web Api Core. In order to install it you need to typeInstall-Package Microsoft.AspNet.WebApi.Core in the Nuget Package Manager Console.

扩展阅读

Mike Stall wrote a good series of blog posts about Web API parameter binding:

Chapter 13. Formatters and Model Binding

Built-In Model Binders

The framework ships with several built-in implementations, but only three of them deserve special attention from a developer:

ModelBindingParameterBinder, FormatterParameterBinder, and HttpRequestParameterBinding, which implement completely different ways of binding a message part to a model.

The first one, ModelBindingParameterBinder, uses an approach borrowed from ASP.NET MVC in which the model is composed of different parts in the message, as if they are Lego building blocks.

The second one, FormatterParameterBinder, relies on formatters that understand all the semantics and formatting of a given media type and know how to serialize or deserialize a model applying those semantics.

Formatters represent a key part of content negotiation and are the preferred method for binding a message body to a model.

Finally, the third one, HttpRequestParameterBinding, is used for supporting scenarios with generic actions that use HttpRequestMessage or HttpResponseMessage instances directly as part of the method signature.

The framework includes a set of formatters out of the box for handling the most common media types such as form-encoded data (FormUrlEncodedMediaTypeFormatter), JSON (JsonMediaTypeFormatter), or XML (XmlMediaTypeFormatter). For other media types, you will have to write your own implementation, or use one of the many implementations provided by the open source community.

JsonMediaTypeFormatter and XmlMediaTypeFormatter

Note:

It is worth mentioning that the JsonMediaTypeFormatter implementation currently uses the Json.NET library internally to serialize/deserialize JSON payloads, and the XmlMediaTypeFormatter implementation uses either the DataContractSerializer or the XmlSerializer classes included in the .NET Framework. This class provides a Boolean property UseXmlSerializer to use the XmlSerializer class or not, which is set to false by default. You can extend these classes to use your libraries of preference for serializing XML or JSON.

Can't bind multiple parameters ('header' and 'parameters') to the request's content.

2019-01-22 16:43:53.812+08:00 ERROR [12]:
System.InvalidOperationException: Can't bind multiple parameters ('header' and 'parameters') to the request's content.
at System.Web.Http.Controllers.HttpActionBinding.ExecuteBindingAsync(HttpActionContext actionContext, CancellationToken cancellationToken)
at System.Web.Http.Controllers.ActionFilterResult.<ExecuteAsync>d__5.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__15.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__15.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at LISA.WebApi.Chile.Helper.CustomMessageHandler.<SendAsync>d__3.MoveNext() in C:\Users\clu\source\repos\Edenred\LISA_6.0.0.0\LISA.CMS.Chile\LISA.WebApi.Chile\Helper\CustomMessageHandler.cs:line 48
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Web.Http.HttpServer.<SendAsync>d__24.MoveNext()

https://stackoverflow.com/questions/51365048/exceptionmessage-cant-bind-multiple-parameters-tenant-and-certificatefile

https://stackoverflow.com/questions/44690905/cant-bind-multiple-parameter-to-the-requests-content-in-web-api-and-angular?rq=1

public string Save(JObject EmpData)
{
dynamic json = EmpData;
A1 Emp=json.Emp.ToObject<A1>();
List<A2> EmpMarks=json.ToObject<List<A2>>();
}

最新文章

  1. Nginx模块参考手册:HTTP核心模块
  2. Office2013插件开发Outlook篇(1)-- 第一个office2013插件
  3. mac
  4. Lombok 安装、入门 - 消除冗长的 java 代码
  5. JVM性能调优监控工具jps、jstack、jmap、jhat、jstat、hprof使用详解
  6. MVC concept
  7. java环境配置笔记
  8. Rightmost Digit
  9. iOS开发中使用[[UIApplication sharedApplication] openURL:]加载其它应用
  10. readint writeint
  11. MyEclipse取消Show in Breadcrumb的方法
  12. Filemon(Filemon文件系统监视)V7.04官方版
  13. Load 数据1
  14. 谈一谈泛型(Generic)
  15. Django里自定义用户登陆及登陆后跳转到登陆前页面的实现
  16. php实现网站四则运算。
  17. 微信小程序选择并上传图片
  18. HTML5动感圆圈
  19. 黄聪:sqlserver 2008修改数据库表的时候错误提示“阻止保存要求重新创建表的更改”
  20. Windows安装MySQL教程

热门文章

  1. HDU 3572(Task Schedule) ISAP做法
  2. BLOCK方式实现OC程序中多个页面判定用户是否登录
  3. responsive and functional programming RxJava
  4. git学习------>写给 Git 初学者的7个建议
  5. MyBatis缓存机制-二级缓存
  6. PHP获取客户端的IP
  7. RTSP客户端接收存储数据(live555库中的openRTSP实例)
  8. pandas(二)函数应用和映射
  9. PHP获取与操作php.ini文件的几个函数示例
  10. C#检测两个文件内容是否相同