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消息。
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)
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