【ASP.NET Web API教程】5.2 发送HTML表单数据:URL编码的表单数据

简介: 原文:【ASP.NET Web API教程】5.2 发送HTML表单数据:URL编码的表单数据注:本文是【ASP.NET Web API系列教程】的一部分,如果您是第一次看本系列教程,请先看前面的内容。
原文: 【ASP.NET Web API教程】5.2 发送HTML表单数据:URL编码的表单数据

注:本文是【ASP.NET Web API系列教程】的一部分,如果您是第一次看本系列教程,请先看前面的内容。

5.2 Sending HTML Form Data
5.2 发送HTML表单数据

本文引自:http://www.asp.net/web-api/overview/working-with-http/sending-html-form-data,-part-1

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编码的表单数据。

  • Overview of HTML Forms
    HTML表单概述
  • Sending Complex Types
    发送复合类型
  • Sending Form Data via AJAX
    通过AJAX发送表单数据
  • Sending Simple Types
    发送简单类型

Overview of HTML Forms
HTML表单概述

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方法:

<form action="api/values" method="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标签属性会指明请求体的格式:

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:
典型地,你要发送的是一个复合类型,它由几个表单控件的值所组成。考虑以下表示状态更新的一个模型:

namespace FormEncode.Models 
{ 
    using System; 
    using System.ComponentModel.DataAnnotations;
public class Update { [Required] [MaxLength(140)] public string Status { get; set; }
public DateTime Date { get; set; } } }

Here is a Web API controller that accepts an Update object via POST.
以下是通过POST接收Update对象的一个Web API控制器。

namespace FormEncode.Controllers 
{ 
    using FormEncode.Models; 
    using System; 
    using System.Collections.Generic; 
    using System.Net; 
    using System.Net.Http; 
    using System.Web; 
    using System.Web.Http; 
public class UpdatesController : ApiController { static readonly Dictionary<Guid, Update> updates = new Dictionary<Guid, Update>();
[HttpPost] [ActionName("Complex")] public HttpResponseMessage PostComplex(Update update) { if (ModelState.IsValid && update != null) { // Convert any HTML markup in the status text. // 转换status文本中的HTML标记。 update.Status = HttpUtility.HtmlEncode(update.Status);
// Assign a new ID. // 赋一个新的ID。 var id = Guid.NewGuid(); updates[id] = update;
// Create a 201 response. // 创建一个201响应。 var response = new HttpResponseMessage(HttpStatusCode.Created) { Content = new StringContent(update.Status) }; response.Headers.Location = new Uri(Url.Link("DefaultApi", new { action = "status", id = id })); return response; } else { return Request.CreateResponse(HttpStatusCode.BadRequest); } }
[HttpGet] public Update Status(Guid id) { Update update; if (updates.TryGetValue(id, out update)) { return update; } else { throw new HttpResponseException(HttpStatusCode.NotFound); } } } }

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表单。

<h1>Complex Type</h1> 
<form id="form1" method="post" action="api/updates/complex"
    enctype="application/x-www-form-urlencoded"> 
    <div> 
        <label for="status">Status</label> 
    </div> 
    <div> 
        <input name="status" type="text" /> 
    </div> 
    <div> 
        <label for="date">Date</label> 
    </div> 
    <div> 
        <input name="date" type="text" /> 
    </div> 
    <div> 
        <input type="submit" value="Submit" /> 
    </div> 
</form>

Notice that the action attribute on the form is the URI of our controller action. Here is the form with some values entered in:
注意,form的action标签属性是控制器动作的URI。以下是已经输入了一些值的表单:

WebAPI5-6

图5-6. 输入了一些数据的表单

When the user clicks Submit, the browser sends an HTTP request similar to the following:
当用户点击“Submit”时,浏览器发送一个类似于以下数据的HTML请求:

POST http://localhost:38899/api/updates/complex HTTP/1.1 
Accept: text/html, application/xhtml+xml, */* 
User-Agent: Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0) 
Content-Type: application/x-www-form-urlencoded
Content-Length: 47 
status=Shopping+at+the+mall.&date=6%2F15%2F2012

Notice that the request body contains the form data, formatted as name/value pairs. Web API automatically converts the name/value pairs into an instance of the Update class.
注意,请求体包含了表单数据,被格式化成“名字/值”对。Web API会自动地把“名字/值”对转换成Update类的实例。

Sending Form Data via AJAX
通过AJAX发送表单数据

When a user submits a form, the browser navigates away from the current page and renders the body of the response message. That’s OK when the response is an HTML page. With a web API, however, the response body is usually either empty or contains structured data, such as JSON. In that case, it makes more sense to send the form data using an AJAX request, so that the page can process the response.
当用户递交表单时,浏览器会离开当前页面,并渲染响应消息体。当响应是HTML页面时,这没问题。然而,对于Web API,响应体通常是空的,或是如JSON那样的结构化数据。在这种情况下,用AJAX请求发送表单数据,以使页面能够处理响应,会更有意义些。

The following code shows how to post form data using jQuery.
以下代码演示如何用jQuery递交表单数据。

 <script type="text/javascript"> 
    $("#form1").submit(function () { 
        var jqxhr = $.post('api/updates/complex', $('#form1').serialize())
            .success(function () { 
                var loc = jqxhr.getResponseHeader('Location'); 
                var a = $('<a/>', { href: loc, text: loc }); 
                $('#message').html(a); 
            }) 
            .error(function () { 
                $('#message').html("Error posting the update."); 
            }); 
        return false; 
    }); 
</script>

The jQuery submit function replaces the form action with a new function. This overrides the default behavior of the Submit button. The serialize function serializes the form data into name/value pairs. To send the form data to the server, call $.post().
jQuery的submit函数用一个新函数替换了表单的action。它重写了Submit按钮的默认行为。serialize函数把表单数据序列化成“名字/值”对。为了将表单数据发送给服务器,调用$.post()

When the request completes, the .success() or .error() handler displays an appropriate message to the user.
当请求完成时,.success().error()处理器会给用户显示一条相应的消息(见图5-7)。

WebAPI5-7

图5-7. 通过AJAX发送表单数据

Sending Simple Types
发送简单类型

In the previous sections, we sent a complex type, which Web API deserialized to an instance of a model class. You can also send simple types, such as a string.
在前一小节中,我们发送的是复合类型,Web API会将其解序列化成一个模型类实例。你也可以发送简单类型,如字符串。

Before sending a simple type, consider wrapping the value in a complex type instead. This gives you the benefits of model validation on the server side, and makes it easier to extend your model if needed.
在发送简单类型之前,请考虑将值封装成复合类型。其好处是你可以在服务器端进行模型验证,并在必要时扩展模型。

The basic steps to send a simple type are the same, but there are two subtle differences. First, in the controller, you must decorate the parameter name with the FromBody attribute.
发送简单类型的基本步骤是相同的,但有两个细微的差别。第一,在控制器中,你必须用FromBody注解属性来修饰参数名。

[HttpPost] 
[ActionName("Simple")] 
public HttpResponseMessage PostSimple([FromBody] string value) 
{ 
    if (value != null) 
    { 
        Update update = new Update() 
        { 
            Status = HttpUtility.HtmlEncode(value), 
            Date = DateTime.UtcNow 
        }; 
var id = Guid.NewGuid(); updates[id] = update;
var response = new HttpResponseMessage(HttpStatusCode.Created) { Content = new StringContent(update.Status) }; response.Headers.Location = new Uri(Url.Link("DefaultApi", new { action = "status", id = id })); return response; } else { return Request.CreateResponse(HttpStatusCode.BadRequest); }

By default, Web API tries to get simple types from the request URI. The FromBody attribute tells Web API to read the value from the request body.
默认地,Web API试图通过请求的URI获取简单类型。FromBody注解属性告诉Web API从请求体读取这个值。

Web API reads the response body at most once, so only one parameter of an action can come from the request body. If you need to get multiple values from the request body, define a complex type.
Web API最多读取响应体一次,因此只有动作的一个参数可以获自请求体。如果需要从请求体得到多个值,需要定义复合类型。

Second, the client needs to send the value with the following format:
第二,客户端需要用以下格式发送这个值:

=value

Specifically, the name portion of the name/value pair must be empty for a simple type. Not all browsers support this for HTML forms, but you create this format in script as follows:
特别地,“名字/值”对的值部分对于简单类型必须为空。并不是所有浏览器对HTML表单都支持这种格式,但你在脚本中按下列方式创建了格式:

$.post('api/updates/simple', { "": $('#status1').val() });

Here is an example form:
以下是一个示例表单:

<h1>Simple Type</h1> 
<form id="form2"> 
    <div> 
        <label for="status">Status</label> 
    </div> 
    <div> 
        <input id="status1" type="text" /> 
    </div> 
    <div> 
        <input type="submit" value="Submit" /> 
    </div> 
</form>

And here is the script to submit the form value. The only difference from the previous script is the argument passed into the post function.
以下是递交表单值的脚本。与前面的脚本唯一的差别是在post函数中传递的参数。

$('#form2').submit(function () { 
    var jqxhr = $.post('api/updates/simple', { "": $('#status1').val() }) 
        .success(function () { 
            var loc = jqxhr.getResponseHeader('Location'); 
            var a = $('<a/>', { href: loc, text: loc }); 
            $('#message').html(a); 
        }) 
        .error(function () { 
            $('#message').html("Error posting the update."); 
        }); 
    return false; 
});

You can use the same approach to send an array of simple types:
可以用同样的办法发送简单类型的数组:

$.post('api/updates/postlist', { "": ["update one", "update two", "update three"] });

Additional Resources
其它资源

Part 2: File Upload and Multipart MIME
第2部分:文件上传与多部分MIME格式(本系列教程的第5.3小节 — 译者注)


看完此文如果觉得有所收获,请给个推荐

目录
相关文章
|
4月前
|
开发框架 前端开发 JavaScript
ASP.NET Web Pages - 教程
ASP.NET Web Pages 是一种用于创建动态网页的开发模式,采用HTML、CSS、JavaScript 和服务器脚本。本教程聚焦于Web Pages,介绍如何使用Razor语法结合服务器端代码与前端技术,以及利用WebMatrix工具进行开发。适合初学者入门ASP.NET。
|
2月前
|
前端开发
【2025优雅草开源计划进行中01】-针对web前端开发初学者使用-优雅草科技官网-纯静态页面html+css+JavaScript可直接下载使用-开源-首页为优雅草吴银满工程师原创-优雅草卓伊凡发布
【2025优雅草开源计划进行中01】-针对web前端开发初学者使用-优雅草科技官网-纯静态页面html+css+JavaScript可直接下载使用-开源-首页为优雅草吴银满工程师原创-优雅草卓伊凡发布
72 1
【2025优雅草开源计划进行中01】-针对web前端开发初学者使用-优雅草科技官网-纯静态页面html+css+JavaScript可直接下载使用-开源-首页为优雅草吴银满工程师原创-优雅草卓伊凡发布
|
5月前
|
前端开发 JavaScript 搜索推荐
HTML与CSS在Web组件化中的核心作用及前端技术趋势
本文探讨了HTML与CSS在Web组件化中的核心作用及前端技术趋势。从结构定义、语义化到样式封装与布局控制,两者不仅提升了代码复用率和可维护性,还通过响应式设计、动态样式等技术增强了用户体验。面对兼容性、代码复杂度等挑战,文章提出了相应的解决策略,强调了持续创新的重要性,旨在构建高效、灵活的Web应用。
91 6
|
5月前
|
前端开发 JavaScript UED
在数字化时代,Web 应用性能优化尤为重要。本文探讨了CSS与HTML在提升Web性能中的关键作用及未来趋势
在数字化时代,Web 应用性能优化尤为重要。本文探讨了CSS与HTML在提升Web性能中的关键作用及未来趋势,包括样式表优化、DOM操作减少、图像优化等技术,并分析了电商网站的具体案例,强调了技术演进对Web性能的深远影响。
77 5
|
4月前
|
开发框架 .NET PHP
ASP.NET Web Pages - 添加 Razor 代码
ASP.NET Web Pages 使用 Razor 标记添加服务器端代码,支持 C# 和 Visual Basic。Razor 语法简洁易学,类似于 ASP 和 PHP。例如,在网页中加入 `@DateTime.Now` 可以实时显示当前时间。
|
4月前
|
搜索推荐 算法 数据挖掘
淘口令真实URL API接口的应用与收益
淘口令作为电商推广利器,通过简短文本引导用户直达商品页,提升购物体验与销售效率。本文探讨淘口令真实URL API接口的应用,包括商品推广、数据分析、跨境电商及社交媒体营销等方面,揭示其在电商领域的巨大潜力与收益。
154 1
|
7月前
|
开发框架 监控 前端开发
在 ASP.NET Core Web API 中使用操作筛选器统一处理通用操作
【9月更文挑战第27天】操作筛选器是ASP.NET Core MVC和Web API中的一种过滤器,可在操作方法执行前后运行代码,适用于日志记录、性能监控和验证等场景。通过实现`IActionFilter`接口的`OnActionExecuting`和`OnActionExecuted`方法,可以统一处理日志、验证及异常。创建并注册自定义筛选器类,能提升代码的可维护性和复用性。
106 3
|
7月前
|
开发框架 .NET 中间件
ASP.NET Core Web 开发浅谈
本文介绍ASP.NET Core,一个轻量级、开源的跨平台框架,专为构建高性能Web应用设计。通过简单步骤,你将学会创建首个Web应用。文章还深入探讨了路由配置、依赖注入及安全性配置等常见问题,并提供了实用示例代码以助于理解与避免错误,帮助开发者更好地掌握ASP.NET Core的核心概念。
169 3
|
7月前
|
前端开发 程序员
【前端web入门第二天】01 html语法实现列表与表格_合并单元格
本文介绍了HTML中的列表与表格的使用方法。列表包括无序列表(`&lt;ul&gt;`嵌套`&lt;li&gt;`)、有序列表(`&lt;ol&gt;`嵌套`&lt;li&gt;`)和定义列表(`&lt;dl&gt;`嵌套`&lt;dt&gt;`和`&lt;dd&gt;`)。
142 19
|
7月前
|
开发框架 前端开发 .NET
VB.NET中如何利用ASP.NET进行Web开发
在VB.NET中利用ASP.NET进行Web开发是一个常见的做法,特别是在需要构建动态、交互式Web应用程序时。ASP.NET是一个由微软开发的开源Web应用程序框架,它允许开发者使用多种编程语言(包括VB.NET)来创建Web应用程序。
172 6