简体   繁体   中英

How to return different Http Status Code in ServiceStack

Hi I am very new to Service Stack and am wondering how can I return a different http status code.

The ones that I need be able to return are:

  1. 204 - processed but no content
  2. 400 - bad request
  3. 404 - not found
  4. 422 - for validation issues
  5. 500 - internal server error

Can Anyone help?

If your Service doesn't return a response, eg has a void method or returns null , ServiceStack automatically returns a 204 No Content response status.

This behavior can be reverted to an empty 200 OK response with:

SetConfig(new HostConfig {
    Return204NoContentForEmptyResponse = false
});

Request DTOs returning empty responses should implement the IReturnVoid marker interface

Custom Error Codes

All other status codes are error status codes which are documented in ServiceStack's Error Handling docs .

Eg It's generally recommended to return the ideal C# Exception and have ServiceStack automatically return the ideal HTTP Error code.

By Default C# Exceptions inheriting from:

  • ArgumentException , SerializationException or FormatException returns a 400 BadRequest
  • NotImplementedException or NotSupportedException returns a 405 MethodNotAllowed
  • FileNotFoundException is return as 404 NotFound
  • AuthenticationException is returned as 401 Unauthorized
  • UnauthorizedAccessException is returned as 403 Forbidden
  • OptimisticConcurrencyException is returned as 409 Conflict
  • All Other normal C# Exceptions are returned as 500 InternalServerError

So any Exceptions inheriting ArgumentException which includes most of the Fluent Validation Exceptions will automatically return the preferred 400 BadRequest .

Other ways to customize HTTP Error Statuses include:

Custom mapping of C# Exceptions to HTTP Error Status

You can change what HTTP Error Status is returned for different Exception Types by configuring them with:

SetConfig(new HostConfig { 
    MapExceptionToStatusCode = {
        { typeof(CustomUnprocessableEntityException), 422 },
        { typeof(CustomerNotFoundException), 404 },
    }
});

Implementing IHasStatusCode

In addition to customizing the HTTP Response Body of C# Exceptions with IResponseStatusConvertible , you can also customize the HTTP Status Code by implementing IHasStatusCode :

public class Custom401Exception : Exception, IHasStatusCode
{
    public int StatusCode => 401;
}

Returning a HttpError

If you want even finer grained control of your HTTP errors you can either throw or return an HttpError letting you customize the Http Headers and Status Code and HTTP Response body to get exactly what you want on the wire:

public object Get(User request) 
{
    throw HttpError.NotFound($"User {request.Name} does not exist");
}

The above returns a 404 NotFound StatusCode on the wire and is a short-hand for:

new HttpError(HttpStatusCode.NotFound, $"User {request.Name} does not exist");

HttpError with a Custom Response DTO

The HttpError can also be used to return a more structured Error Response with:

var responseDto = new ErrorResponse { 
    ResponseStatus = new ResponseStatus {
        ErrorCode = typeof(ArgumentException).Name,
        Message = "Invalid Request",
        Errors = new List<ResponseError> {
            new ResponseError {
                ErrorCode = "NotEmpty",
                FieldName = "Company",
                Message = "'Company' should not be empty."
            }
        }
    }
};

throw new HttpError(HttpStatusCode.BadRequest, "ArgumentException") {
    Response = responseDto,
}; 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM