简体   繁体   English

如何在ServiceStack中返回不同的Http状态码

[英]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.嗨,我对服务堆栈很陌生,想知道如何返回不同的 http 状态代码。

The ones that I need be able to return are:我需要能够返回的是:

  1. 204 - processed but no content 204 - 已处理但没有内容
  2. 400 - bad request 400 - 错误的请求
  3. 404 - not found 404 - 未找到
  4. 422 - for validation issues 422 - 验证问题
  5. 500 - internal server error 500内部服务器错误

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.如果您的 Service 没有返回响应,例如有一个void方法或返回null ,ServiceStack 会自动返回204 No Content响应状态。

This behavior can be reverted to an empty 200 OK response with:此行为可以恢复为空的200 OK响应:

SetConfig(new HostConfig {
    Return204NoContentForEmptyResponse = false
});

Request DTOs returning empty responses should implement the IReturnVoid marker interface请求返回空响应的 DTO 应实现IReturnVoid标记接口

Custom Error Codes自定义错误代码

All other status codes are error status codes which are documented in ServiceStack's Error Handling docs .所有其他状态代码都是错误状态代码,它们记录在 ServiceStack 的错误处理文档中

Eg It's generally recommended to return the ideal C# Exception and have ServiceStack automatically return the ideal HTTP Error code.例如,通常建议返回理想的 C# Exception并让 ServiceStack 自动返回理想的 HTTP 错误代码。

By Default C# Exceptions inheriting from:默认 C# 异常继承自:

  • ArgumentException , SerializationException or FormatException returns a 400 BadRequest ArgumentExceptionSerializationExceptionFormatException返回400 BadRequest
  • NotImplementedException or NotSupportedException returns a 405 MethodNotAllowed NotImplementedExceptionNotSupportedException返回405 MethodNotAllowed
  • FileNotFoundException is return as 404 NotFound FileNotFoundException作为404 NotFound返回
  • AuthenticationException is returned as 401 Unauthorized AuthenticationException返回为401 Unauthorized
  • UnauthorizedAccessException is returned as 403 Forbidden UnauthorizedAccessException作为403 Forbidden返回
  • OptimisticConcurrencyException is returned as 409 Conflict OptimisticConcurrencyException作为409 Conflict返回
  • All Other normal C# Exceptions are returned as 500 InternalServerError所有其他正常的 C# 异常都返回为500 InternalServerError

So any Exceptions inheriting ArgumentException which includes most of the Fluent Validation Exceptions will automatically return the preferred 400 BadRequest .因此,任何继承ArgumentException异常(包括大多数Fluent 验证异常)都将自动返回首选的400 BadRequest

Other ways to customize HTTP Error Statuses include:自定义 HTTP 错误状态的其他方法包括:

Custom mapping of C# Exceptions to HTTP Error Status C# 异常到 HTTP 错误状态的自定义映射

You can change what HTTP Error Status is returned for different Exception Types by configuring them with:您可以通过配置以下内容来更改为不同的异常类型返回的 HTTP 错误状态:

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

Implementing IHasStatusCode实现 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 :除了使用IResponseStatusConvertible自定义 C# 异常的 HTTP 响应正文之外,您还可以通过实现IHasStatusCode自定义 HTTP 状态代码:

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

Returning a HttpError返回一个 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:如果您想对 HTTP 错误进行更细粒度的控制,您可以抛出返回HttpError允许您自定义Http 标头状态代码以及 HTTP 响应正文,以在网络上获得您想要的内容:

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:以上在线路上返回一个404 NotFound StatusCode 并且是以下内容的简写:

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

HttpError with a Custom Response DTO带有自定义响应 DTO 的 HttpError

The HttpError can also be used to return a more structured Error Response with: HttpError也可用于返回更结构化的错误响应:

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,
}; 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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