0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Postされたjson文字列を ASP.NET Web API側で取得する方法

Last updated at Posted at 2021-05-19

Postされたjson文字列を ASP.NET Web API側で取得する方法

ASP.NET Web APIでは、jsonデータが自動的にマッピングされとても便利なのですが、
Postされた値(Request.Content.Bodyのような)を読むプロパティーが見つからず、ロギングがデバッグ時に不便でなりませんでした。

Stack Overflowも漁ってみましたが、やり方が見つからないためデバッグで原因を探して取得する方法を調査しまいsた

サンプルソース

    public class ProductsController : ApiController
    {
        public OutputValue Post(InputValue input)
        {
            // ★ Postされたデータを文字列で取得したい
            var output = new OutputValue();
            return output;
        }
    }

取得する方法

  • Requestからstreamを取得しても、読み取り終わっているため先頭にSeekする必要があります。
public OutputValue Post(InputValue input)
{
    // RequestからStreamを取得(streamがプロパティーとして公開されていため下記手順で取得する)
    var requestStream = this.Request.Content.ReadAsStreamAsync().Result;
    // streamはフレームワーク側の処理で最後まで読み込み終わっている。再度読み込むため先頭へSeekする
    requestStream.Seek(0, System.IO.SeekOrigin.Begin);
    // 文字列として取得したいのでStreamReader経由で読み取る
    var sr = new System.IO.StreamReader(requestStream);
    // 文字列を最後まで取得する
    var jsonString = sr.ReadToEnd();
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?