本文代碼
https://github.com/wuhaibo/readPlainTextDotNetCoreWepApi
總有些時候我們希望獲得Request body 的純文本 那么怎么做呢?很簡單。如下所示
public string GetJsonString([FromBody]string content) { return "content: " + content ; }
測試結果如下
request: POST http://localhost:5000/api/values/GetJsonString HTTP/1.1 Accept-Encoding: gzip,deflate Content-Type: application/json Content-Length: 6 Host: localhost:5000 Connection: Keep-Alive User-Agent: Apache-HttpClient/4.1.1 (java 1.5) "test" response: HTTP/1.1 200 OK Date: Wed, 07 Mar 2018 14:36:37 GMT Content-Type: text/plain; charset=utf-8 Server: Kestrel Transfer-Encoding: chunked content: test
可以看到content被賦值test。 但有個問題request body的內容必須是合法的json而且request 的media type也得是json
舉個例子,
request: POST http://localhost:5000/api/values/GetJsonString HTTP/1.1 Accept-Encoding: gzip,deflate Content-Type: application/xml Content-Length: 4 Host: localhost:5000 Connection: Keep-Alive User-Agent: Apache-HttpClient/4.1.1 (java 1.5) test response: HTTP/1.1 200 OK Date: Wed, 07 Mar 2018 14:31:07 GMT Content-Type: text/plain; charset=utf-8 Server: Kestrel Transfer-Encoding: chunked content:
可以看到由於request body的內容 test 並不是個合法的xml,所以我們返回的content是空。
有個更好的方法 如下所示,這種方法不論是media type都可以獲得request body 的純文本
public string GetJsonString3(string content) { var reader = new StreamReader(Request.Body); var contentFromBody = reader.ReadToEnd(); return "content: " + content + " contentFromBody: " + contentFromBody; }
測試結果
request: POST http://localhost:5000/api/values/GetJsonString3 HTTP/1.1 Accept-Encoding: gzip,deflate Content-Type: application/xml Content-Length: 4 Host: localhost:5000 Connection: Keep-Alive User-Agent: Apache-HttpClient/4.1.1 (java 1.5) test response: HTTP/1.1 200 OK Date: Wed, 07 Mar 2018 14:43:59 GMT Content-Type: text/plain; charset=utf-8 Server: Kestrel Transfer-Encoding: chunked content: contentFromBody: test
可以看到contentFromBody中我們得到了request body的內容。 注意參數沒有[FromBody]這個屬性 如果加了這個屬性,那么如果request body內容匹配request的media type那么Request.body的position會被置於結尾的位置。 舉個例子
public string GetJsonString2([FromBody]string content) { var reader = new StreamReader(Request.Body); var contentFromBody = reader.ReadToEnd(); Request.Body.Position = 0; var reader2 = new StreamReader(Request.Body); var contentFromBody2 = reader2.ReadToEnd(); return "content: " + content + " contentFromBody: " + contentFromBody + " contentFromBody2: " + contentFromBody2; }
測試結果
request: POST http://localhost:5000/api/values/GetJsonString2 HTTP/1.1 Accept-Encoding: gzip,deflate Content-Type: application/json Content-Length: 4 Host: localhost:5000 Connection: Keep-Alive User-Agent: Apache-HttpClient/4.1.1 (java 1.5) test response: HTTP/1.1 200 OK Date: Wed, 07 Mar 2018 14:53:03 GMT Content-Type: text/plain; charset=utf-8 Server: Kestrel Transfer-Encoding: chunked content: contentFromBody: contentFromBody2: test
