I am using asp.net core 2.1, I need to emulate some existing behavior when returning errors in an api whereby the response includes a custom object:
return this.BadRequest(
new ApiError
{
// The corresponding integer response code.
Status = StatusCodes.Status400BadRequest,
// The matching short text code.
Code = "BadRequest",
// A detailed context specific message.
Message = "Some message"
});
My question is, asp.net core brought the Microsoft.AspNetCore.Http.StatusCodes class with integer fields that indicate the response codes, however the field names are not something I want to expose for example by Code = nameof(StatusCodes.Status400BadRequest).
What is the modern means to generate the response description BadRequest in this case without magic strings?
I could use System.Net.HttpStatusCode.BadRequest and nameof(System.Net.HttpStatusCode.BadRequest) however that seems to ignore newer conventions?
I am not trying to convert return types, the controller and action signatures are already well defined. I want to ensure I am using a concise means to accommodate existing consumers that expect an object with the fields required, and I want to do this without magic strings or multiple unrelated classes if possible.
I imagine the use case is more common than not and more elaborate facility exists to accomplish this?
BadRequestfunction sets the status code and status text appropriately. The reason Microsoft moved toStatusCodeswas precisely to move away from hard-coding things like this. Now everyone's wondering how to hard-code things like this :). You could just callToStringon theHttpStatusCodeas well. See Get HTTP status code descriptions in ASP.Net CoreHttpResponseMessagetoIActionResult, that is not related.