1
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 5 years have passed since last update.

APIControllerで無名クラスを返す場合のContentの取得方法

Posted at

1.問題点

APIControllerを使用してPostを送る場合、
IHttpActionResultを返り値にする場合、以下のように無名クラスで値を返すことがあるが、
その場合、Contentの値を取得することができない。

例:


    [ApiVersion("1.0")]
    [RoutePrefix("api/login")]
    public class LoginController : ApiController
    {

        [Route("")]
        [HttpPost, BodyRequired]
        public IHttpActionResult Post([FromBody]Login.Request postRequest)
        {
                --------

                return Ok(new
                {
                    Response = response
                });
        }

        private void Login()
        {

            _login = new LoginController();
            _login.Request = new HttpRequestMessage()
            {
                RequestUri = new Uri("----略----")
            };

            _req = new Login.Request
            {
                --------
            };

            _login.Configuration = new HttpConfiguration();

            var rp = _login.Post(_req)

        }

上記だと、Post()の返り値がIHttpActionResultのため、Contentが取得できない。
他の型に変換しようにも無名クラスのため変換できない。
01.png

2.解決方法

以下のようにExecuteAsyncを使用すると、Contentが取得できる。

            var rp = _login.Post(_req).ExecuteAsync(CancellationToken.None);
            var r = rp.Result.Content.ReadAsStringAsync().Result;
1
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
1
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?