ASP.NET Odata Web API的错误处理

use*_*779 12 c# odata asp.net-web-api

我很想知道在ODataController中引发异常的最佳实践是什么.

如果在方法中引发异常,则默认情况下会将其转换为响应代码500,并且内容包含有关错误的详细信息.我希望明确响应代码,并在无效密钥的情况下发送400.

例如:如果输入请求具有无效密钥,则希望返回400的HttpResponseCode,并且内容应该具有类似于引发异常的错误详细信息.

非常感谢您的投入

Iva*_*gin 20

OData(至少从v3开始)使用特定的json来表示错误:

{
    "error": {
        "code": "A custom error code",
        "message": {
            "lang": "en-us",
            "value": "A custom long message for the user." 
        },
        "innererror": {
            "trace": [...],
            "context": {...}
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Microsoft .Net包含Microsoft.Data.OData.ODataError和Microsoft.Data.OData.ODataInnerError类,以在服务器端形成OData错误.

要形成正确的OData错误响应(HttpResponseMessage),其中包含错误详细信息,您可以:

1)使用System.Web.OData.Extensions.HttpRequestMessageExtensions.CreateErrorResponse方法在控制器的动作中形成并返回HttpResponseMessage

return Request.CreateErrorResponse(HttpStatusCode.Conflict, new ODataError { ErrorCode="...", Message="...", MessageLanguage="..." }));
Run Code Online (Sandbox Code Playgroud)

2)使用相同的方法抛出HttpResponseException来创建HttpResponseMessage

throw new HttpResponseException(
    Request.CreateErrorResponse(HttpStatusCode.NotFound,  new ODataError { ErrorCode="...", Message="...", MessageLanguage="..." }));
Run Code Online (Sandbox Code Playgroud)

3)抛出自定义类型异常并使用Web Api动作过滤器进行转换

public class CustomExceptionFilterAttribute : ExceptionFilterAttribute
{
    public override void OnException(HttpActionExecutedContext context)
    {
        if (context.Exception is CustomException)
        {
            var e = (CustomException)context.Exception;

            var response = context.Request.CreateErrorResponse(e.StatusCode, new ODataError
            {
                ErrorCode = e.StatusCodeString,
                Message = e.Message,
                MessageLanguage = e.MessageLanguage
            });
            context.Response = response;
        }
        else
            base.OnException(context);
    }
}
Run Code Online (Sandbox Code Playgroud)


Vla*_*mir 1

使用HttpResponseException,
例如throw new HttpResponseException(HttpStatusCode.NotFound);。详细信息可以在这里
找到。