在c#webapi中,哪种状态代码适用于哪种类型的异常



我在webapi2中工作,我需要知道哪种状态代码适用于哪种异常类型。我找到了一些异常类型的状态代码。但我需要完整的异常与http状态代码列表。

if (ex.GetType() == typeof(NotImplementedException))
            {
                _exception = new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.NotImplemented, ex.Message));
            }
            else if (ex.GetType() == typeof(NullReferenceException))
            {
                _exception = new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.LengthRequired, ex.Message));
            }
            else if (ex.GetType() == typeof(OutOfMemoryException))
            {
                _exception = new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.UnsupportedMediaType, ex.Message));
            }
            else if (ex.GetType() == typeof(OverflowException))
            {
                _exception = new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.RequestEntityTooLarge, ex.Message));
            }
            else if (ex.GetType() == typeof(StackOverflowException))
            {
                _exception = new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.RequestEntityTooLarge, ex.Message));
            }
            else if (ex.GetType() == typeof(TypeInitializationException))
            {
                _exception = new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.NoContent, ex.Message));
            }
            else if (ex.GetType() == typeof(HttpException))
            {
                _exception = new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex.Message));
            }

尝试将.NET异常映射到HTTP状态代码是不可能的。我看到使用NotAcceptable是因为开发人员似乎认为该请求"不可接受",而实际上NotAcceptable(406)用于内容协商,并且您的代码将OverflowException映射到RequestEntityTooLarge(413)。这会通知客户端发送的请求对于服务器来说太大,而实际上服务器上的溢出显然是InternalServerError(500)。

只需将所有错误映射到BadRequest(400)、Forbidden(403)和InternalServerError(500)(也许还有一些其他合适的状态代码),但不要更改状态代码的含义-它们是HTTP标准的一部分。

您可以自由地在消息内容中详细说明错误,您也可以在代码中这样做。

相关内容

最新更新