Reputation: 5075
I have written method that returns the result in the object. I need to capture current HttpStatusCode rather than I create my own and save in the following object before returning a result
[HttpPost]
public ActionResult CreateUser([FromBody]UsereDto user)
{
try
{
var data = UserService.CreateUser(user);
var result = new ResultDto
{
Ok = true,
Data = data,
Error = "No",
StatusCode = HttpStatusCode. ???????????????
};
return Ok(result);
}
catch(Exception exp)
{
var errorResult = new ResultDto
{
Ok = false,
Data = null,
Error = exp.ToString()
StatusCode = ????????????
};
return Ok(errorResult);
}
}
Upvotes: 1
Views: 1262
Reputation: 30385
I am not 100% sure what do you want to achieve or why do you even want that since HTTP Response already will contain an http status, so returning it additionally in a JSON response does not add more information than is already available.
But you can just hardcode the status since it is always 200 in your example, unless there is some error during serialization of the response, etc.
Right after your ???
line you do return an Ok()
response that will return 200.
Upvotes: 1
Reputation: 4178
You don't need to create your own status code inside dto...
return Ok(errorResult);
will return 200 with error and this is bad.
Instead, you should return BadRequestResult(errorResult) and ui will receive 500 result containing your DTO.
Also, instead of return Ok(result);
, you can return OkResult(result)
and this will return 200 to UI, also containing your DTO...
Also, you should extract Dto creation to it's own method in separate class, to follow DRY and single responsibility principles..
Upvotes: 0
Reputation: 395
Can't capture existing http code you can manually enter http codes yourself.
For Example: Created Code=201 Error Code =400 BadRequest:301 NotFound:404
return StatusCode(200,object);
You can also return it this way.
Upvotes: 2