I have a C# application that can throw a locked exception. I'd like to return a Microsoft.AspNetCore.Mvc.StatusCode of HttpStatusCode.Locked and add a custom message to the response.
Currently in the controller if I use:
[ProducesResponseType(StatusCodes.Status423Locked)]
public async Task<IActionResult> GetSomething(Guid id)
{
try
{
await MyService
.GetAsync(id)
.ConfigureAwait(false);
return Ok();
}
catch (IsLockedException ex)
{
return StatusCode((int)HttpStatusCode.Locked, ex.Message);
}
The it just returns the text of the exception message like:
The organisation 6ad1f1c0-2c47-4849-acbb-9eca56b568cf is offline.
However, if I change the return to:
return StatusCode((int)HttpStatusCode.Locked);
It will then return the following response:
{
"status": 423,
"traceId": "|8f3060e2-4338773910204188."
}
So is there a way for me to keep both the "status" and the custom text in the response?
Don't use a string when calling StatusCode()
, use an object, and it will be properly serialized.
Example:
return StatusCode((int)HttpStatusCode.Locked, new { status = (int)HttpStatusCode.Locked, message = ex.Message });