user2916547
user2916547

Reputation: 2033

How to return both custom HTTP status code and content?

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?

Upvotes: 7

Views: 24432

Answers (4)

thinkOfaNumber
thinkOfaNumber

Reputation: 2883

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

Upvotes: 2

Sakura Isayeki
Sakura Isayeki

Reputation: 118

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

Upvotes: 0

Thangadurai
Thangadurai

Reputation: 2621

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

Upvotes: 3

adem caglin
adem caglin

Reputation: 24151

You can use ContentResult:

return new ContentResult() { Content = myContent, StatusCode = myCode };

Upvotes: 24

Related Questions