哪个状态代码适用于c#web api中的哪种类型的异常

时间:2014-09-18 09:27:53

标签: c# asp.net-web-api

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

            }

1 个答案:

答案 0 :(得分:0)

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

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

您可以自由地详细说明您在代码中所做的邮件内容中的错误。

相关问题