FormUrlEncodedMediaTypeFormatter 与 JQueryMvcFormUrlEncodedFormatter

Pas*_*cal 5 formatter asp.net-web-api asp.net-web-api2

我创建了一个默认的 web api 项目,其中至少加载了这 2 个媒体格式化程序。两者都用于相同的内容类型:

FormUrlEncodedMediaTypeFormatter: application/x-www-form-urlencoded
JQueryMvcFormUrlEncodedFormatter: application/x-www-form-urlencoded
Run Code Online (Sandbox Code Playgroud)

当我用enctype="application/x-www-form-urlencoded"它做一个简单的 http post 表单时,它只适用于JQueryMvcFormUrlEncodedFormatter,这意味着我发送的复杂对象在服务器端不为空。

当我JQueryMvcFormUrlEncodedFormatter在应用程序启动时删除格式化程序并再次执行简单的 http post 表单时,我希望它再次工作,但它没有。

我得到一个异常,没有加载适当的格式化程序。

那不是真的-实际上-

为什么它不起作用?

聚苯乙烯

我发现这就是区别:

– System.Net.Http.Formatting.FormUrlEncodedMediaTypeFormatter, for handling HTML form URL-encoded data
– System.Web.Http.ModelBinding.JQueryMvcFormUrlEncodedFormatter, for handling model-bound HTML form URL-encoded data
Run Code Online (Sandbox Code Playgroud)

但我不明白其中的区别!

我什至不使用 jquery 来发布我的表单:

<form role="form" method="post" action="api/values"    enctype="application/x-www-form-urlencoded">
    <input type="text" class="form-control" name="firstName" placeholder="Enter first name">
    <input type="text" class="form-control" name="lastName" placeholder="Enter last name">
    <button type="submit" class="btn btn-default">Submit</button>
</form>
Run Code Online (Sandbox Code Playgroud)

omi*_*nes 4

FormUrlEncodedMediaTypeFormatterapplication/x-www-form-urlencoded主体绑定到FormDataCollection类型,并且仅绑定到该类型。

JQueryMvcFormUrlEncodedFormatter但是,使用可用的 ModelBinder 首先解析主体FormDataCollection,然后使用第一个兼容的 ModelBinder 将其解析为最终模型。这就像混合模型绑定方法和媒体类型格式化方法,据我所知,WebAPI 文档中的任何地方都没有对此进行解释。

默认情况下,这两个格式化程序都会注册。这是我通过阅读WebAPI源代码推断出来的。