webapi是如何绑定参数的(How WebAPI does Parameter Binding)
由于工作原因,要使用ASP.NET WEBAPI(非mvc webapi),前几天时间一直很紧张,所以webapi一直将就用,今天下午好不容易有时间终于看了下,解决了自己一直疑惑的问题,在此特贴出,给大家分享。
Here’s an overview of how WebAPI binds parameters to an action method. I’ll describe how parameters can be read, the set of rules that determine which technique is used, and then provide some examples.
[update] Parameter binding is ultimately about taking a HTTP request and converting it into .NET types so that you can have a better action signature.
The request message has everything about the request, including the incoming URL with query string, content body, headers, etc. Eg, without parameter binding, every action would have to take the request message and manually extract the parameters, kind of like this:
public object MyAction(HttpRequestMessage request)
{
// make explicit calls to get parameters from the request object
int id = int.Parse(request.RequestUri.ParseQueryString().Get("id")); // need error logic!
Customer c = request.Content.ReadAsAsync<Customer>().Result; // should be async!
// Now use id and customer
}
That’s ugly, error prone, repeats boiler plate code, is missing corner cases, and hard to unit test. You want the action signature to be something more relevant like:
public object MyAction(int id, Customer c) { }
So how does WebAPI convert from a request message into real parameters like id and customer?
Model Binding vs. Formatters
There are 2 techniques for binding parameters: Model Binding and Formatters. In practice, WebAPI uses model binding to read from the query string and Formatters to read from the body.
(1) Using Model Binding:
ModelBinding is the same concept as in MVC, which has been written about a fair amount (such as here). Basically, there are “ValueProviders” which supply pieces of data such as query string parameters, and then a model binder assembles those pieces into an object.
(2) Using Formatters:
Formatters (see the MediaTypeFormatter class) are just traditional serializers with extra metadata such as the associated content type. WebAPI gets the list of formatters from the HttpConfiguration, and then uses the request’s content-type to select an appropriate formatter. WebAPI has some default formatters. The default JSON formatter is JSON.Net. There is an Xml formatter and a FormUrl formatter that uses JQuery’s syntax.
The key method is MediaTypeFormatter.ReadFromStreayAsync, which looks :
public virtual Task<object> ReadFromStreamAsync(
Type type,
Stream stream,
HttpContentHeaders contentHeaders,
IFormatterLogger formatterLogger)
Type is the parameter type being read, which is passed to the serializer. Stream is the request’s content stream. The read function then reads the stream, instantiates an object, and returns it.
HttpContentHeaders are just from the request message. IFormatterLogger is a callback interface that a formatter can use to log errors while reading (eg, malformed data for the given type).
Both model binding and formatters support validation and log rich error information. However, model binding is significantly more flexible.
When do we use which?
Here are the basic rules to determine whether a parameter is read with model binding or a formatter:
- If the parameter has no attribute on it, then the decision is made purely on the parameter’s .NET type.“Simple types” uses model binding. Complex types uses the formatters. A “simple type” includes:primitives, TimeSpan, DateTime, Guid, Decimal, String, or something with a TypeConverter that converts from strings.
- You can use a [FromBody] attribute to specify that a parameter should be from the body.
- You can use a [ModelBinder] attribute on the parameter or the parameter’s type to specify that a parameter should be model bound. This attribute also lets you configure the model binder. [FromUri] is a derived instance of [ModelBinder] that specifically configures a model binder to only look in the URI.
- The body can only be read once. So if you have 2 complex types in the signature, at least one of them must have a [ModelBinder] attribute on it.
It was a key design goal for these rules to be static and predictable.
Only one thing can read the body
A key difference between MVC and WebAPI is that MVC buffers the content (eg, request body). This means that MVC’s parameter binding can repeatedly search through the body to look for pieces of the parameters. Whereas in WebAPI, the request body (an HttpContent) may be a read-only, infinite, non-buffered, non-rewindable stream.
That means that parameter binding needs to be very careful about not reading the stream unless it’s guaranteeing to bind a parameter. The action body may want to read the stream directly, and so WebAPI can’t assume that it owns the stream for parameter binding. Consider this example action:
// Action saves the request’s content into an Azure blob
public Task PostUploadfile(string destinationBlobName)
{
// string should come from URL, we’ll read content body ourselves.
Stream azureStream = OpenAzureStorage(destinationBlobName); // stream to write to azure
return this.Request.Content.CopyToStream(azureStream); // upload body contents to azure.
}
The parameter is a simple type, and so it’s pulled from the query string. Since there are no complex types in the action signature, webAPI never even touches the request content stream, and so the action body can freely read it.
Some examples
Here are some examples of various requests and how they map to action signatures.
/?id=123&name=bob
void Action(int id, string name) // both parameters are simple types and will come from url
/?id=123&name=bob
void Action([FromUri] int id, [FromUri] string name) // paranoid version of above.
void Action([FromBody] string name); // explicitly read the body as a string.
public class Customer { // a complex object
public string Name { get; set; }
public int Age { get; set; }
}
/?id=123
void Action(int id, Customer c) // id from query string, c is a complex object, comes from body via a formatter.
void Action(Customer c1, Customer c2) // error! multiple parameters attempting to read from the body
void Action([FromUri] Customer c1, Customer c2) // ok, c1 is from the URI and c2 is from the body
void Action([ModelBinder(MyCustomBinder)] SomeType c) // Specifies a precise model binder to use to create the parameter.
[ModelBinder(MyCustomBinder)] public class SomeType { } // place attribute on type declaration to apply to all parameter instances
void Action(SomeType c) // attribute on c’s declaration means it uses model binding.
Differences with MVC
Here are some differences between MVC and WebAPI’s parameter binding:
- MVC only had model binders and no formatters. That’s because MVC would model bind over the request’s body (which it commonly expected to just be FormUrl encoded), whereas WebAPI uses a serializer over the request’s body.
- MVC buffered the request body, and so could easily feed it into model binding. WebAPI does not buffer the request body, and so does not model bind against the request body by default.
- WebAPI’s binding can be determined entirely statically based off the action signature types. For example, in WebAPI, you know statically whether a parameter will bind against the body or the query string. Whereas in MVC, the model binding system would search both body and query string.
webapi是如何绑定参数的(How WebAPI does Parameter Binding)的更多相关文章
- webapi 控制器接收POST参数时必须以对象的方式接收
webapi 控制器接收POST参数时必须以对象的方式接收
- ASP.NET Core WebApi 返回统一格式参数(Json 中 Null 替换为空字符串)
相关博文:ASP.NET Core WebApi 返回统一格式参数 业务场景: 统一返回格式参数中,如果包含 Null 值,调用方会不太好处理,需要替换为空字符串,示例: { "respon ...
- WebApi接口 - 如何在应用中调用webapi接口
很高兴能再次和大家分享webapi接口的相关文章,本篇将要讲解的是如何在应用中调用webapi接口:对于大部分做内部管理系统及类似系统的朋友来说很少会去调用别人的接口,因此可能在这方面存在一些困惑,希 ...
- 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(参数绑定)
Parameter Binding in ASP.NET Web API(参数绑定) 导航 阅读本文之前,您也可以到Asp.Net Web API 2 系列导航进行查看 http://www.cnbl ...
- 【WebApi系列】浅谈HTTP在WebApi开发中的运用
WebApi系列文章 [01]浅谈HTTP在WebApi开发中的运用 [02]聊聊WebApi体系结构 [03]详解WebApi参数的传递 [04]详解WebApi测试和PostMan [05]浅谈W ...
- [PDO绑定参数]使用PHP的PDO扩展进行批量更新操作
最近有一个批量更新数据库表中某几个字段的需求,在做这个需求的时候,使用了PDO做参数绑定,其中遇到了一个坑. 方案选择 笔者已知的做批量更新有以下几种方案: 1.逐条更新 这种是最简单的方案,但无疑也 ...
- Yii 1.1 DAO绑定参数实例
<?php $sql = "SELECT * FROM admin_user WHERE user_name=:uname AND password LIKE :c"; $c ...
- Hibernate绑定参数
使用绑定参数的优势: 我们为什么要使用绑定命名参数?任何一个事物的存在都是有其价值的,具体到绑定参数对于HQL查询来说,主要有以下两个主要优势:①. 可以利用数据库实施性能优化 因为对Hibernat ...
随机推荐
- FZU 2213——Common Tangents——————【两个圆的切线个数】
Problem 2213 Common Tangents Accept: 7 Submit: 8Time Limit: 1000 mSec Memory Limit : 32768 KB ...
- jQuery中的DOM操作——《锋利的JQuery》
jQuery封装了大量DOM操作的API,极大提高了操作DOM节点的效率. 1.查找节点 通过我们上一节介绍了JQuery选择器,可以非常轻松地查找节点元素.不过,这时得到的是jQuery对象,只能使 ...
- TD不换行 nowrap属性
表格table的td单元格中,文字长了往往会撑开单元格,但是如果table都不够宽了,就换行了好像(不要较真其他情况,我只说会换行的情况).换行后的表格显得乱糟糟,不太好看,我不喜欢这样的换行.当然可 ...
- js之正则表达式基础
字符串是编程时涉及到的最多的一种数据结构,对字符串进行操作的需求几乎无处不在.比如判断一个字符串是否是合法的Email地址,虽然可以编程提取@前后的子串,再分别判断是否是单词和域名,但这样做不但麻烦, ...
- 使用durid的ConfigFilter对数据库密码加密
<!-- 配置dbcp数据源 --> <bean id="remoteDS" class="org.apache.commons.dbcp.BasicD ...
- git rebase 和 git merge 总结
git merge 和 git rebase 都是用于合并分支,但二者是存在区别的. 在使用时,记住以下两点: 当你从 remote 去 pull 的时候,永远使用 rebase(除了一个例外) 当你 ...
- 【数据库】3.0 MySQL入门学习(三)——Windows系统环境下MySQL安装
1.0 我的操作系统是window10 专业版 64位.,不过至少windows7以上系统都是一样的. 关于MySQL如何下载,请参考博文: [数据库]2.0 如何获得MySQL以及MySQL安装 h ...
- 06_Jedis完成MySQL的条件查询案例
[概述] 假设现在有一个User表,其中有id,name,age,sex等字段,完成如下要求的SQL语句为: 1.查找所有age=18 的User ; 2.查找所有sex="M"( ...
- 【HTML5】HTML5 综合
HTML5教程: 视频教程:http://www.socss.cn/html5视频教程大集合/ DCloud关于HTML5:http://ask.dcloud.net.cn/docs 开发工具:HBu ...
- QTableview 只显示横向线
#include <QApplication> #include <QTableWidget> #include <QPainter> #include <Q ...