在我的Web Api项目中,我尝试将可能在其他应用程序(如WCF服务)中使用的单独模块中的业务逻辑分开。ActionFilterAttribute.OnActionExecuted在json正文中使用下划线的前缀属性
由于这个原因,为了创建一个常规的例外方式,我创建了一个继承自异常的类,并且传递了一个包含我的业务错误的对象。
所以应用程序应该处理从业务层抛出的异常。
在这个特定的情况下,我创建了一个过滤器,我已经使全局,所以所有控制器的操作都有这个过滤器。该过滤器的代码是:
Public Class MyCustomActionFilterAttribute
Inherits System.Web.Http.Filters.ActionFilterAttribute
Public Overrides Sub OnActionExecuting(actionContext As Http.Controllers.HttpActionContext)
If Not actionContext.ModelState.IsValid Then
Dim Errors As New List(Of ErrorResult)
For Each lError In actionContext.ModelState.Values.SelectMany(Function(x) x.Errors)
If Not String.IsNullOrWhiteSpace(lError.ErrorMessage) Then
Errors.Add(New ErrorResult(lError.ErrorMessage))
Else
Errors.Add(New ErrorResult With {.Code = ErrorCode.GenericValidationError, .Description = lError.Exception.Message})
End If
Next
actionContext.Response = New HttpResponseMessage(System.Net.HttpStatusCode.BadRequest) With {
.Content = New ObjectContent(Of List(Of ErrorResult)) _
(Errors, New System.Net.Http.Formatting.JsonMediaTypeFormatter)
}
End If
End Sub
Public Overrides Sub OnActionExecuted(actionExecutedContext As Http.Filters.HttpActionExecutedContext)
MyBase.OnActionExecuted(actionExecutedContext)
If Not actionExecutedContext.Exception Is Nothing Then
Dim Errors As New List(Of ErrorResult)
If actionExecutedContext.Exception.GetType Is GetType(MyCustomException) Then
Errors.Add(CType(actionExecutedContext.Exception, MyCustomException).ErrorResult)
Else
Errors.Add(New ErrorResult With {.Code = ErrorCode.GenericError, .Description = actionExecutedContext.Exception.Message})
End If
actionExecutedContext.Response = New HttpResponseMessage(System.Net.HttpStatusCode.BadRequest) With {
.Content = New ObjectContent(Of List(Of ErrorResult)) _
(Errors, New System.Net.Http.Formatting.JsonMediaTypeFormatter)
}
End If
End Sub
End Class
与上述我想实现一个常见的方式呈现例外。所以我有一个类ErrorResult
,它只有两个属性Code
和Description
。
当我与ModelState中的一个问题我得到一个不错的JSON数组如下所示:
[{Code: -1001, Description: "Error Description"}]
这是我希望看到的。这是由OnActionExecuting
方法创建的。
我的问题是,当OnActionExecuted
方法存在错误,我得到的回应是:
[{_Code: -1001, _Description: "Error Description"}]
为什么我得到这些下划线和我怎么可能摆脱他们的?