Receiving IActionResult from WebApi












3















I have created Web API, and my problem is reading results from it to client.



WebApi method which creating user:



[HttpPost]
public IActionResult PostNewUser([FromBody]UserDto userDto)
{
if (userDto == null)
return BadRequest(nameof(userDto));
IUsersService usersService = GetService<IUsersService>();
var id = usersService.Add(userDto);
return Created("api/users/", id.ToString());
}


And the client which want to call API code is:



public int CreateUser(UserDto dto)
{
using (HttpClient client = new HttpClient())
{
string endpoint = ApiQuery.BuildAddress(Endpoints.Users);
var json = new StringContent(JsonConvert.SerializeObject(dto), Encoding.UTF8, "application/json");
var postReult = client.PostAsync(endpoint, json).Result;
return 1; //??
}
}


It works, response gives 201 (Created) but I have no idea how to return correct result, which should be:



/api/users/id_of_created_user


I'm using netcore2.0 in both projects










share|improve this question

























  • When you have postResult, you should first check its IsSuccessStatusCode property and then read the Content in one way or another (like calling ReadStreamAsync() for example). I would also recommend using async / await all the way avoiding calling Result on a returned Task.

    – Stas Ivanov
    Jan 2 at 9:40











  • you mean something like this ? var result = await postReult.Content.ReadAsStringAsync();

    – Ric
    Jan 2 at 9:41











  • currently what you received in var postReult?

    – er-sho
    Jan 2 at 9:44











  • the problem is that if i get postRestul.Content.ReadAsAnything() it doesnt give me 'api/users/newUserId' - it gives me only newUserId

    – SharkyShark
    Jan 2 at 9:48
















3















I have created Web API, and my problem is reading results from it to client.



WebApi method which creating user:



[HttpPost]
public IActionResult PostNewUser([FromBody]UserDto userDto)
{
if (userDto == null)
return BadRequest(nameof(userDto));
IUsersService usersService = GetService<IUsersService>();
var id = usersService.Add(userDto);
return Created("api/users/", id.ToString());
}


And the client which want to call API code is:



public int CreateUser(UserDto dto)
{
using (HttpClient client = new HttpClient())
{
string endpoint = ApiQuery.BuildAddress(Endpoints.Users);
var json = new StringContent(JsonConvert.SerializeObject(dto), Encoding.UTF8, "application/json");
var postReult = client.PostAsync(endpoint, json).Result;
return 1; //??
}
}


It works, response gives 201 (Created) but I have no idea how to return correct result, which should be:



/api/users/id_of_created_user


I'm using netcore2.0 in both projects










share|improve this question

























  • When you have postResult, you should first check its IsSuccessStatusCode property and then read the Content in one way or another (like calling ReadStreamAsync() for example). I would also recommend using async / await all the way avoiding calling Result on a returned Task.

    – Stas Ivanov
    Jan 2 at 9:40











  • you mean something like this ? var result = await postReult.Content.ReadAsStringAsync();

    – Ric
    Jan 2 at 9:41











  • currently what you received in var postReult?

    – er-sho
    Jan 2 at 9:44











  • the problem is that if i get postRestul.Content.ReadAsAnything() it doesnt give me 'api/users/newUserId' - it gives me only newUserId

    – SharkyShark
    Jan 2 at 9:48














3












3








3


0






I have created Web API, and my problem is reading results from it to client.



WebApi method which creating user:



[HttpPost]
public IActionResult PostNewUser([FromBody]UserDto userDto)
{
if (userDto == null)
return BadRequest(nameof(userDto));
IUsersService usersService = GetService<IUsersService>();
var id = usersService.Add(userDto);
return Created("api/users/", id.ToString());
}


And the client which want to call API code is:



public int CreateUser(UserDto dto)
{
using (HttpClient client = new HttpClient())
{
string endpoint = ApiQuery.BuildAddress(Endpoints.Users);
var json = new StringContent(JsonConvert.SerializeObject(dto), Encoding.UTF8, "application/json");
var postReult = client.PostAsync(endpoint, json).Result;
return 1; //??
}
}


It works, response gives 201 (Created) but I have no idea how to return correct result, which should be:



/api/users/id_of_created_user


I'm using netcore2.0 in both projects










share|improve this question
















I have created Web API, and my problem is reading results from it to client.



WebApi method which creating user:



[HttpPost]
public IActionResult PostNewUser([FromBody]UserDto userDto)
{
if (userDto == null)
return BadRequest(nameof(userDto));
IUsersService usersService = GetService<IUsersService>();
var id = usersService.Add(userDto);
return Created("api/users/", id.ToString());
}


And the client which want to call API code is:



public int CreateUser(UserDto dto)
{
using (HttpClient client = new HttpClient())
{
string endpoint = ApiQuery.BuildAddress(Endpoints.Users);
var json = new StringContent(JsonConvert.SerializeObject(dto), Encoding.UTF8, "application/json");
var postReult = client.PostAsync(endpoint, json).Result;
return 1; //??
}
}


It works, response gives 201 (Created) but I have no idea how to return correct result, which should be:



/api/users/id_of_created_user


I'm using netcore2.0 in both projects







c# asp.net-web-api asp.net-core asp.net-core-webapi






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Jan 2 at 10:34









Nkosi

119k17137201




119k17137201










asked Jan 2 at 9:30









SharkySharkSharkyShark

1338




1338













  • When you have postResult, you should first check its IsSuccessStatusCode property and then read the Content in one way or another (like calling ReadStreamAsync() for example). I would also recommend using async / await all the way avoiding calling Result on a returned Task.

    – Stas Ivanov
    Jan 2 at 9:40











  • you mean something like this ? var result = await postReult.Content.ReadAsStringAsync();

    – Ric
    Jan 2 at 9:41











  • currently what you received in var postReult?

    – er-sho
    Jan 2 at 9:44











  • the problem is that if i get postRestul.Content.ReadAsAnything() it doesnt give me 'api/users/newUserId' - it gives me only newUserId

    – SharkyShark
    Jan 2 at 9:48



















  • When you have postResult, you should first check its IsSuccessStatusCode property and then read the Content in one way or another (like calling ReadStreamAsync() for example). I would also recommend using async / await all the way avoiding calling Result on a returned Task.

    – Stas Ivanov
    Jan 2 at 9:40











  • you mean something like this ? var result = await postReult.Content.ReadAsStringAsync();

    – Ric
    Jan 2 at 9:41











  • currently what you received in var postReult?

    – er-sho
    Jan 2 at 9:44











  • the problem is that if i get postRestul.Content.ReadAsAnything() it doesnt give me 'api/users/newUserId' - it gives me only newUserId

    – SharkyShark
    Jan 2 at 9:48

















When you have postResult, you should first check its IsSuccessStatusCode property and then read the Content in one way or another (like calling ReadStreamAsync() for example). I would also recommend using async / await all the way avoiding calling Result on a returned Task.

– Stas Ivanov
Jan 2 at 9:40





When you have postResult, you should first check its IsSuccessStatusCode property and then read the Content in one way or another (like calling ReadStreamAsync() for example). I would also recommend using async / await all the way avoiding calling Result on a returned Task.

– Stas Ivanov
Jan 2 at 9:40













you mean something like this ? var result = await postReult.Content.ReadAsStringAsync();

– Ric
Jan 2 at 9:41





you mean something like this ? var result = await postReult.Content.ReadAsStringAsync();

– Ric
Jan 2 at 9:41













currently what you received in var postReult?

– er-sho
Jan 2 at 9:44





currently what you received in var postReult?

– er-sho
Jan 2 at 9:44













the problem is that if i get postRestul.Content.ReadAsAnything() it doesnt give me 'api/users/newUserId' - it gives me only newUserId

– SharkyShark
Jan 2 at 9:48





the problem is that if i get postRestul.Content.ReadAsAnything() it doesnt give me 'api/users/newUserId' - it gives me only newUserId

– SharkyShark
Jan 2 at 9:48












2 Answers
2






active

oldest

votes


















0














In the Web API either construct the created location URL manually



[HttpPost]
public IActionResult PostNewUser([FromBody]UserDto userDto) {
if (userDto == null)
return BadRequest(nameof(userDto));
IUsersService usersService = GetService<IUsersService>();
var id = usersService.Add(userDto);
//construct desired URL
var url = string.Format("api/users/{0}",id.ToString());
return Created(url, id.ToString());
}


Or use one of the CreateAt* overloads



//return 201 created status code along with the 
//controller, action, route values and the actual object that is created
return CreatedAtAction("ActionName", "ControllerName", new { id = id }, id.ToString());

//OR

//return 201 created status code along with the
//route name, route value, and the actual object that is created
return CreatedAtRoute("RouteName", new { id = id }, id.ToString());


In the client, the location is retrieved from the header of the response.



status HttpClient client = new HttpClient();

public async Task<int> CreateUser(UserDto dto) {
string endpoint = ApiQuery.BuildAddress(Endpoints.Users);
var json = new StringContent(JsonConvert.SerializeObject(dto), Encoding.UTF8, "application/json");

var postResponse = await client.PostAsync(endpoint, json);

var location = postResponse.Headers.Location;// api/users/{id here}

var id = await postResponse.Content.ReadAsAsync<int>();

return id;
}


You also appear to be sending the id as part of the response which can be retrieved from the response content.



Note the refactoring of HttpClient to avoid creating an instance every time which can lead to socked exhaustion that can cause errors.






share|improve this answer































    0














    Or you can always return JsonResult and return JSON object from the server with required data for the client. Here is an example to use



    https://www.c-sharpcorner.com/UploadFile/2ed7ae/jsonresult-type-in-mvc/






    share|improve this answer























      Your Answer






      StackExchange.ifUsing("editor", function () {
      StackExchange.using("externalEditor", function () {
      StackExchange.using("snippets", function () {
      StackExchange.snippets.init();
      });
      });
      }, "code-snippets");

      StackExchange.ready(function() {
      var channelOptions = {
      tags: "".split(" "),
      id: "1"
      };
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function() {
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled) {
      StackExchange.using("snippets", function() {
      createEditor();
      });
      }
      else {
      createEditor();
      }
      });

      function createEditor() {
      StackExchange.prepareEditor({
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader: {
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      },
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      });


      }
      });














      draft saved

      draft discarded


















      StackExchange.ready(
      function () {
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54003949%2freceiving-iactionresult-from-webapi%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      2 Answers
      2






      active

      oldest

      votes








      2 Answers
      2






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      0














      In the Web API either construct the created location URL manually



      [HttpPost]
      public IActionResult PostNewUser([FromBody]UserDto userDto) {
      if (userDto == null)
      return BadRequest(nameof(userDto));
      IUsersService usersService = GetService<IUsersService>();
      var id = usersService.Add(userDto);
      //construct desired URL
      var url = string.Format("api/users/{0}",id.ToString());
      return Created(url, id.ToString());
      }


      Or use one of the CreateAt* overloads



      //return 201 created status code along with the 
      //controller, action, route values and the actual object that is created
      return CreatedAtAction("ActionName", "ControllerName", new { id = id }, id.ToString());

      //OR

      //return 201 created status code along with the
      //route name, route value, and the actual object that is created
      return CreatedAtRoute("RouteName", new { id = id }, id.ToString());


      In the client, the location is retrieved from the header of the response.



      status HttpClient client = new HttpClient();

      public async Task<int> CreateUser(UserDto dto) {
      string endpoint = ApiQuery.BuildAddress(Endpoints.Users);
      var json = new StringContent(JsonConvert.SerializeObject(dto), Encoding.UTF8, "application/json");

      var postResponse = await client.PostAsync(endpoint, json);

      var location = postResponse.Headers.Location;// api/users/{id here}

      var id = await postResponse.Content.ReadAsAsync<int>();

      return id;
      }


      You also appear to be sending the id as part of the response which can be retrieved from the response content.



      Note the refactoring of HttpClient to avoid creating an instance every time which can lead to socked exhaustion that can cause errors.






      share|improve this answer




























        0














        In the Web API either construct the created location URL manually



        [HttpPost]
        public IActionResult PostNewUser([FromBody]UserDto userDto) {
        if (userDto == null)
        return BadRequest(nameof(userDto));
        IUsersService usersService = GetService<IUsersService>();
        var id = usersService.Add(userDto);
        //construct desired URL
        var url = string.Format("api/users/{0}",id.ToString());
        return Created(url, id.ToString());
        }


        Or use one of the CreateAt* overloads



        //return 201 created status code along with the 
        //controller, action, route values and the actual object that is created
        return CreatedAtAction("ActionName", "ControllerName", new { id = id }, id.ToString());

        //OR

        //return 201 created status code along with the
        //route name, route value, and the actual object that is created
        return CreatedAtRoute("RouteName", new { id = id }, id.ToString());


        In the client, the location is retrieved from the header of the response.



        status HttpClient client = new HttpClient();

        public async Task<int> CreateUser(UserDto dto) {
        string endpoint = ApiQuery.BuildAddress(Endpoints.Users);
        var json = new StringContent(JsonConvert.SerializeObject(dto), Encoding.UTF8, "application/json");

        var postResponse = await client.PostAsync(endpoint, json);

        var location = postResponse.Headers.Location;// api/users/{id here}

        var id = await postResponse.Content.ReadAsAsync<int>();

        return id;
        }


        You also appear to be sending the id as part of the response which can be retrieved from the response content.



        Note the refactoring of HttpClient to avoid creating an instance every time which can lead to socked exhaustion that can cause errors.






        share|improve this answer


























          0












          0








          0







          In the Web API either construct the created location URL manually



          [HttpPost]
          public IActionResult PostNewUser([FromBody]UserDto userDto) {
          if (userDto == null)
          return BadRequest(nameof(userDto));
          IUsersService usersService = GetService<IUsersService>();
          var id = usersService.Add(userDto);
          //construct desired URL
          var url = string.Format("api/users/{0}",id.ToString());
          return Created(url, id.ToString());
          }


          Or use one of the CreateAt* overloads



          //return 201 created status code along with the 
          //controller, action, route values and the actual object that is created
          return CreatedAtAction("ActionName", "ControllerName", new { id = id }, id.ToString());

          //OR

          //return 201 created status code along with the
          //route name, route value, and the actual object that is created
          return CreatedAtRoute("RouteName", new { id = id }, id.ToString());


          In the client, the location is retrieved from the header of the response.



          status HttpClient client = new HttpClient();

          public async Task<int> CreateUser(UserDto dto) {
          string endpoint = ApiQuery.BuildAddress(Endpoints.Users);
          var json = new StringContent(JsonConvert.SerializeObject(dto), Encoding.UTF8, "application/json");

          var postResponse = await client.PostAsync(endpoint, json);

          var location = postResponse.Headers.Location;// api/users/{id here}

          var id = await postResponse.Content.ReadAsAsync<int>();

          return id;
          }


          You also appear to be sending the id as part of the response which can be retrieved from the response content.



          Note the refactoring of HttpClient to avoid creating an instance every time which can lead to socked exhaustion that can cause errors.






          share|improve this answer













          In the Web API either construct the created location URL manually



          [HttpPost]
          public IActionResult PostNewUser([FromBody]UserDto userDto) {
          if (userDto == null)
          return BadRequest(nameof(userDto));
          IUsersService usersService = GetService<IUsersService>();
          var id = usersService.Add(userDto);
          //construct desired URL
          var url = string.Format("api/users/{0}",id.ToString());
          return Created(url, id.ToString());
          }


          Or use one of the CreateAt* overloads



          //return 201 created status code along with the 
          //controller, action, route values and the actual object that is created
          return CreatedAtAction("ActionName", "ControllerName", new { id = id }, id.ToString());

          //OR

          //return 201 created status code along with the
          //route name, route value, and the actual object that is created
          return CreatedAtRoute("RouteName", new { id = id }, id.ToString());


          In the client, the location is retrieved from the header of the response.



          status HttpClient client = new HttpClient();

          public async Task<int> CreateUser(UserDto dto) {
          string endpoint = ApiQuery.BuildAddress(Endpoints.Users);
          var json = new StringContent(JsonConvert.SerializeObject(dto), Encoding.UTF8, "application/json");

          var postResponse = await client.PostAsync(endpoint, json);

          var location = postResponse.Headers.Location;// api/users/{id here}

          var id = await postResponse.Content.ReadAsAsync<int>();

          return id;
          }


          You also appear to be sending the id as part of the response which can be retrieved from the response content.



          Note the refactoring of HttpClient to avoid creating an instance every time which can lead to socked exhaustion that can cause errors.







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Jan 2 at 10:32









          NkosiNkosi

          119k17137201




          119k17137201

























              0














              Or you can always return JsonResult and return JSON object from the server with required data for the client. Here is an example to use



              https://www.c-sharpcorner.com/UploadFile/2ed7ae/jsonresult-type-in-mvc/






              share|improve this answer




























                0














                Or you can always return JsonResult and return JSON object from the server with required data for the client. Here is an example to use



                https://www.c-sharpcorner.com/UploadFile/2ed7ae/jsonresult-type-in-mvc/






                share|improve this answer


























                  0












                  0








                  0







                  Or you can always return JsonResult and return JSON object from the server with required data for the client. Here is an example to use



                  https://www.c-sharpcorner.com/UploadFile/2ed7ae/jsonresult-type-in-mvc/






                  share|improve this answer













                  Or you can always return JsonResult and return JSON object from the server with required data for the client. Here is an example to use



                  https://www.c-sharpcorner.com/UploadFile/2ed7ae/jsonresult-type-in-mvc/







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Jan 2 at 10:45









                  Kishore KollaKishore Kolla

                  694




                  694






























                      draft saved

                      draft discarded




















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54003949%2freceiving-iactionresult-from-webapi%23new-answer', 'question_page');
                      }
                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      MongoDB - Not Authorized To Execute Command

                      How to fix TextFormField cause rebuild widget in Flutter

                      in spring boot 2.1 many test slices are not allowed anymore due to multiple @BootstrapWith