有没有办法在 Web Api 控制器中处理表单发布数据? [英] Is there a way to handle form post data in a Web Api controller?
问题描述
在ASP.NET MVC
中,可以访问表单发布数据:
In ASP.NET MVC
, one can access the form post data:
var thisData = Request.Form["this.data"];
是否可以在 Web API
中实现相同的功能 ApiController?
Is it possible to achieve the same functionality in a Web API
ApiController?
推荐答案
ASP.NET Web API 在处理不同的 HTTP 场景(尤其是流式处理)方面变得更加健壮.因此,只有媒体类型的格式化程序通常会接触内容并且必须使内容保持一致.
ASP.NET Web API has become significantly more robust in dealing with different HTTP scenarios - especially streaming. As such only media type formatters normally touch the content and have to make a coherence of the content.
在 ASP.NET MVC 中,application/x-www-form-urlencoded
内容类型是一等公民(并且被特别对待,因为这是 95% 的 POST 请求的内容类型)并且我们有 FormsCollection
来提供访问中的字典访问,只要它被定义为输入参数.
In ASP.NET MVC, application/x-www-form-urlencoded
content type is a first class citizen (and treated especially since this is the content type of 95% of the POST requests) and we have the FormsCollection
to provide dictionary access in access, whenever it is defined as an input parameter.
在 ASP.NET Web API 中,application/x-www-form-urlencoded
是另一种内容类型,应该由其 MediaTypeFormatter 读取.因此,ASP.NET Web API 无法对 Forms
做出任何假设.
In ASP.NET Web API, application/x-www-form-urlencoded
is yet another content type, and supposed to be read by its MediaTypeFormatter. As such ASP.NET Web API cannot make any assumption about the Forms
.
ASP.NET Web API 中的正常方法是将表单表示为模型,以便媒体类型格式化程序对其进行反序列化.另一种方法是将动作的参数定义为 NameValueCollection
:
The normal approach in ASP.NET Web API is to represent the form as a model so the media type formatter deserializes it. Alternative is to define the actions's parameter as NameValueCollection
:
public void Post(NameValueCollection formData)
{
var value = formData["key"];
}
这篇关于有没有办法在 Web Api 控制器中处理表单发布数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!