本文是【ASP.NET Web API系列教程】的一部分,若是您是第一次看本系列教程,请先看前面的内容。html
5.2 Sending HTML Form Data
5.2 发送HTML表单数据web
本文引自:http://www.asp.net/web-api/overview/working-with-http/sending-html-form-data,-part-1api
By Mike Wasson|June 15, 2012
做者:Mike Wasson | 日期:2012-6-15服务器
Part 1: Form-urlencoded Data
第1部分:URL编码的表单数据网络
This article shows how to post form-urlencoded data to a Web API controller.
本文显示如何向Web API控制器递交URL编码的表单数据。app
Download the completed project.
下载完整的项目。asp.net
Overview of HTML Forms
HTML表单概述ide
HTML forms use either GET or POST to send data to the server. The method attribute of the form element gives the HTTP method:
HTML表单使用GET或POST将数据发送给服务器。form元素的method标签属性给出HTTP方法:post
The default method is GET. If the form uses GET, the form data is encoded in the URI as a query string. If the form uses POST, the form data is placed in the request body. For POSTed data, the enctype attribute specifies the format of the request body:
默认方法是GET。若是form使用GET,表单数据做为查询字符串被编码到URI中。若是form使用POST,表单数据被放在请求体中。对于POST的数据,enctype标签属性会指明请求体的格式:ui
enctype | Description 描述 |
---|---|
application/x-www-form-urlencoded | Form data is encoded as name/value pairs, similar to a URI query string. This is the default format for POST. 表单数据被编码成“名字/值”对,相似于URI查询字符串。这是POST的默认格式。 |
multipart/form-data | Form data is encoded as a multipart MIME message. Use this format if you are uploading a file to the server. 表单数据被编码成多部分MIME消息。若是把文件上传到服务器,使用的是这种格式。 |
MIME指Multipurpose Internet Mail Extensions — 多用途互联网邮件扩展,它是经过网络传递邮件消息的一个互联网标准。MIME规定了用于表示各类数据类型的符号化方法。在HTTP协议中,对HTTP消息的内容类型也采用了MIME的这种表示数据类型的方法。上述enctype标签属性意为“编码类型”,就是用来指定HTTP消息的Content-Type(内容类型)报头属性。给这个标签属性所指定的值必须是MIME对Content-Type所规定的值之一。上表中即是MIME中关于内容类型的其中两个值。更多内容请参阅MIME的有关资料 — 译者注
Part 1 of this article looks at x-www-form-urlencoded format. Part 2 describes multipart MIME.
本文的第1部分考察x-www-form-urlencoded格式。第2部分描述多部分MIME。
Sending Complex Types
发送复合类型
Typically, you will send a complex type, composed of values taken from several form controls. Consider the following model that represents a status update:
典型地,你要发送的是一个复合类型,它由几个表单控件的值所组成。考虑如下表示状态更新的一个模型:
Here is a Web API controller that accepts an Update object via POST.
如下是经过POST接收Update对象的一个Web API控制器。
This controller uses action-based routing, so the route template is "api/{controller}/{action}/{id}". The client will post the data to "/api/updates/complex".
这个控制器使用了“基于动做的路由(本系列教程的第4.1小节 — 译者注)”,所以,路由模板是“api/{controller}/{action}/{id}”。客户端会把这些数据递交给“/api/updates/complex”。
Now let’s write an HTML form for users to submit a status update.
如今,让咱们编写一个用户递交状态更新的HTML表单。