I personally use StatusCode(int code, object value)
to return a HTTP Code and Message/Attachment/else from a Controller.
Now here i'm assuming that you're doing this in a plain normal ASP.NET Core Controller, so my answer may be completely wrong depending on your use case.
A quick example of use in my code (i'll comment out all the non-necessary stuff) :
[HttpPost, Route("register")]
public async Task<IActionResult> Register([FromBody] RegisterModel model)
{
/* Checking code */
if (userExists is not null)
{
return StatusCode(409, ErrorResponse with { Message = "User already exists." });
}
/* Creation Code */
if (!result.Succeeded)
{
return StatusCode(500, ErrorResponse with { Message = $"User creation has failed.", Details = result.Errors });
}
// If everything went well...
return StatusCode(200, SuccessResponse with { Message = "User created successfuly." });
}
If you were to ask, this example, while shown with .NET 5, works well with previous ASP.NET versions. But since we're on the subject of .NET 5, i'd like to point out that ErrorResponse
and SuccessResponse
are records used to standardize my responses, as seen here :
public record Response
{
public string Status { get; init; }
public string Message { get; init; }
public object Details { get; init; }
}
public static class Responses
{
public static Response SuccessResponse => new() { Status = "Success", Message = "Request carried out successfully." };
public static Response ErrorResponse => new() { Status = "Error", Message = "Something went wrong." };
}
Now, as you said you're using Custom HTTP Codes, using int
for codes is plain perfect.
It does what it says on the tin, so this should work nicely for you ;)
Content
method does a bit more, like setting the Content Type header to plain text. – Mastrianni