0

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?

4
  • Why would it be common to have a property that says 400 Bad Request when the HTTP status code tells you that? Commented Aug 14, 2018 at 21:59
  • 2
    It's not entirely clear what you mean. The BadRequest function sets the status code and status text appropriately. The reason Microsoft moved to StatusCodes was precisely to move away from hard-coding things like this. Now everyone's wondering how to hard-code things like this :). You could just call ToString on the HttpStatusCode as well. See Get HTTP status code descriptions in ASP.Net Core Commented Aug 14, 2018 at 22:00
  • @CamiloTerevinto, your comment above answers your first comment. I am required to an object than implements the fields described, this is distinct from the response code in semantics. The handlers in the consumer code utilize the object's properties. I am looking for a concise way to accommodate it. I am not trying to convert HttpResponseMessage to IActionResult, that is not related. Commented Aug 14, 2018 at 22:28
  • @HereticMonkey The more I look at this, I continue to arrive at the same conclusion. I am going to look into accommodating the native functionality in the consuming code. Commented Aug 14, 2018 at 23:11

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.