Parameter Binding in ASP.NET Web API
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能够对应上就可以了。
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:
- How Web API does Parameter Binding
- MVC Style parameter binding for Web API
- How to bind to custom objects in action signatures in MVC/Web API
- How to create a custom value provider in Web API
- Web API Parameter binding under the hood
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.
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()
public string Save(JObject EmpData)
{
dynamic json = EmpData;
A1 Emp=json.Emp.ToObject<A1>();
List<A2> EmpMarks=json.ToObject<List<A2>>();
}
Parameter Binding in ASP.NET Web API的更多相关文章
- Parameter Binding in ASP.NET Web API(参数绑定)
Parameter Binding in ASP.NET Web API(参数绑定) 导航 阅读本文之前,您也可以到Asp.Net Web API 2 系列导航进行查看 http://www.cnbl ...
- Asp.Net Web API 2第十六课——Parameter Binding in ASP.NET Web API(参数绑定)
导航 阅读本文之前,您也可以到Asp.Net Web API 2 系列导航进行查看 http://www.cnblogs.com/aehyok/p/3446289.html. 本文主要来讲解以下内容: ...
- Parameter Binding in ASP.NET Web API #Reprinted
http://www.asp.net/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api
- ASP.NET Web API 学习【转】
转自:http://www.cnblogs.com/babycool/p/3922738.html 来看看对于一般前台页面发起的get和post请求,我们在Web API中要如何来处理. 这里我使用J ...
- ASP.NET Web API Model-ActionBinding
ASP.NET Web API Model-ActionBinding 前言 前面的几个篇幅把Model部分的知识点划分成一个个的模块来讲解,而在控制器执行过程中分为好多个过程,对于控制器执行过程(一 ...
- Asp.Net Web API 2第六课——Web API路由和动作选择
Asp.Net Web API 导航 Asp.Net Web API第一课——入门http://www.cnblogs.com/aehyok/p/3432158.html Asp.Net Web AP ...
- asp.net web api [FromBody]参数
Using jQuery to POST [FromBody] parameters to Web API 时间2013-04-04 00:28:17 Encosia原文 http://encosia ...
- 【ASP.NET Web API教程】2.3.5 用Knockout.js创建动态UI
原文:[ASP.NET Web API教程]2.3.5 用Knockout.js创建动态UI 注:本文是[ASP.NET Web API系列教程]的一部分,如果您是第一次看本博客文章,请先看前面的内容 ...
- 【ASP.NET Web API教程】4.2 路由与动作选择
原文:[ASP.NET Web API教程]4.2 路由与动作选择 注:本文是[ASP.NET Web API系列教程]的一部分,如果您是第一次看本系列教程,请先看前面的内容. 4.2 Routing ...
随机推荐
- Codeforces Round #364 (Div. 1)B. Connecting Universities
题目链接:传送门 题目大意:n个点构成一棵树,给定 k*2 点,要分成 k 组,使每组点之间的距离之和最大. 题目思路:因为是求距离之和最大,所以我们可以知道这样一个性质.如果以一条边为界,两边的子树 ...
- Mycat安装及测试分片总结
1.安装jdk1.72.连接实际mysql数据库 用命令行工具或图形化客户端,连接mysql,创建DEMO所用三个分片数据库:(默认schema.xml中的配置需要三个库) CREATE databa ...
- iOS 7 计算字符串高度
- (float)width:(NSString *)str font:(UIFont *)font { NSDictionary *attribute = @{NSFontAttributeName ...
- 选项卡jQuery(ele).each()
$("li").each(index){ $(this).mouseover(fucntion(){ $("div.contentin" ...
- 【CSS选择器】理解汇总和记录
1.选择器中符号含义汇总(这部分包含了对选择器的通用理解): 1.1.多元素组合符号:(共6个,一个是CSS3的)(适用所有元素:ID组合,类组合,属性组合,标签组合,伪类组合,以及以上所有混合组合) ...
- mysql 获取id最大值
数据库表中id列不为自动增加,需要程序来增加id的SQL SELECTCASE IFNULL(MAX(id),1)WHEN 1 THEN 1ELSE MAX(id) + 1END AS newmaxi ...
- 系统根据用户cookies,为用户打上各种标签
DSP营销学院_品友学院 | 品友推广官网 http://e.ipinyou.com/school_article40.html 智能算法+动态出价=最大发挥推广费用的价值 针对每一个曝光进行甄别和竞 ...
- IO流入门-第十三章-File相关
/* java.io.File 1.File和流无关,不能通过该类完成文件的读写 2.File是文件和目录路径名的抽象变现形式. */ import java.io.*; public class F ...
- Properties 集合
Map Hashtable Properties 特点: 该集合中的键和值都是字符串类型 集合中的数据可以保存到流中, 或者从流中获取 应用: 通常该集合用于操作以键值对形式存在的配置文件 常用方法: ...
- 原!!mysql,几十万条数据中随机抽取1万以内的数据
想了几种方法: 1.将所有符合条件的对象集合都查出来,在代码里做随机. 2.先查出所有符合条件的id,再代码随机需要抽查数量的id,再 到数据库 中 in. 3.利用order by rand() l ...