How to return both custom HTTP status code and content?
Asked Answered
M

4

7

I have an WebApi Controller written in ASP.NET Core and would like to return a custom HTTP status code along with custom content.

I am aware of:

return new HttpStatusCode(myCode)

and

return Content(myContent)

and I am looking for something along the lines of:

return Content(myCode, myContent)

or some in built mechanism that already does that. So far I have found this solution:

var contentResult = new Content(myContent);
contentResult.StatusCode = myCode;
return contentResult;

is another recommended way of achieving this?

Mastrianni answered 14/11, 2016 at 13:37 Comment(0)
A
23

You can use ContentResult:

return new ContentResult() { Content = myContent, StatusCode = myCode };
Aloes answered 14/11, 2016 at 13:48 Comment(2)
Thank you - that looks more readable than my code. Possibly the Content method does a bit more, like setting the Content Type header to plain text.Mastrianni
In .NET 6.0, this looks like: return new ContentResult() { Content = myContent, StatusCode = StatusCodes.Status400BadRequest };Kinny
M
3

You need to use HttpResponseMessage

Below is a sample code

// GetEmployee action  
public HttpResponseMessage GetEmployee(int id)  
{  
   Employee emp = EmployeeContext.Employees.Where(e => e.Id == id).FirstOrDefault();  
   if (emp != null)  
   {  
      return Request.CreateResponse<Employee>(HttpStatusCode.OK, emp);  
   }  
   else  
   {  
      return Request.CreateErrorResponse(HttpStatusCode.NotFound, " Employee Not Found");  
   }  

} 

More info here

Misfeasance answered 14/11, 2016 at 13:49 Comment(0)
I
2

I know it's an old question but you can do this for non-string responses by using ObjectResult.

If you can't inherit from ControllerBase:

return new ObjectResult(myContent)
{
    StatusCode = myCode
};

If you are in a class inheriting from ControllerBase then StatusCode is the simplest:

return StatusCode(myCode, myContent);
Instantly answered 18/11, 2020 at 1:13 Comment(0)
B
0

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 ;)

Bittern answered 16/11, 2020 at 7:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.