Receiving IActionResult from WebApi
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
add a comment |
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
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 invar 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
add a comment |
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
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
c# asp.net-web-api asp.net-core asp.net-core-webapi
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 invar 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
add a comment |
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 invar 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
add a comment |
2 Answers
2
active
oldest
votes
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.
add a comment |
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/
add a comment |
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
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
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.
add a comment |
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.
add a comment |
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.
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.
answered Jan 2 at 10:32


NkosiNkosi
119k17137201
119k17137201
add a comment |
add a comment |
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/
add a comment |
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/
add a comment |
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/
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/
answered Jan 2 at 10:45


Kishore KollaKishore Kolla
694
694
add a comment |
add a comment |
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.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
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
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