[整理]Ajax Post请求下的Form Data和Request Payload

Ajax Post请求下的Form Data和Request Payload

通常情况下,我们通过Post提交表单,以键值对的形式存储在请求体中。此时的reqeuest headers会有Content-Type为application/x-www-form-urlencoded 的实体头字段来标明当前的表单数据的内容形式,在Chrome F12下的Form Data中可以查看到。

而如果直接使用XmlHttpRequest Post提交,除非手动添加头Content-Type:application/x-www-form-urlencoded, 发送的表单参数不会Form Data中,而是在存储在Request Payload中, 这和文件上传的情况是一致的,不同是请求头Content-Type不同。前者默认是text/plain,后者是multipart/form-data; boundary=----WebKitFormBoundaryIQTaiWwGiqjLQYUB。


那么,什么是Request Payload? 在了解Payload这个术语前,还需了解以下几个术语:

消息(Http Message)

http中定义了2种消息,Request和Response消息。

4.1 Message Types

Request (section 5) and Response (section 6) messages use the generic
message format of RFC 822 [9] for transferring entities (the payload
of the message). Both types of message consist of a start-line, zero
or more header fields (also known as "headers"), an empty line (i.e.,
a line with nothing preceding the CRLF) indicating the end of the
header fields, and possibly a message-body.

实体(Entity)

1.3 Terminology

entity

The information transferred as the payload of a request or
response. An entity consists of metainformation in the form of
entity-header fields and content in the form of an entity-body, as
described in section 7.

信息被作为请求或响应的有效负荷被传递。通俗的说就是,实体是指作为请求或者响应消息的有效载荷而传输的信息。

例如,当用户想浏览某个Web页面时,HTTP请求消息种的请求方法,响应消息中的状态码都不是有效载荷,它们都是为了实现文件下载这一最终目的而在客户于服务器之间传送的额外消息:而用户所要浏览的HTML文件及其元消息(文件大小,最近修改时间等)才是有效载荷。

有效载荷(Payload)

通过前面的http定义可以了解到什么是payload。

请求request消息或响应response消息中可能会包含真正要传递的数据,这个数据我们就称为消息的有效负荷,对应着就是request payload,response payload。


知道了什么是Request Payload,那服务端是如何接收并解析出我们通过Request Payload所传递的特殊格式的数据呢(比如表单键值对参数或复杂的json对象)?
一般服务端程序会根据头字段中的Content-type的值来做特定的处理,如x-www-form-urlencoded。有一篇文章说到如何在java servlet里通过扩展来处理request payload的形式的参数。

那么ASP.NET 里又是怎样处理的呢?是否也需要我们自行扩展呢?

我们知道XmlHttpRequest.send()默认不设置content-type头字段,服务器一般默认为text/plain。如果我们发送复杂的json格式的情况下,应该手动设置为application/json,这样通过在服务端程序中根据该字段进行相应的处理和解析,从而使数据可以在服务端正确解析称为可能。

回到ASP.NET WEB API中,有各种自定义的方式类解析复杂类型的数据,且不限于json格式。
http://www.asp.net/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api

参考

原文地址:https://www.cnblogs.com/Benoly/p/4341272.html