私の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
ちょうど2つのプロパティCode
とDescription
を持っている。
私は次のように素敵なJSON配列を得るかにModelStateに問題があります。
[{Code: -1001, Description: "Error Description"}]
私が見てみたいものです。これはOnActionExecuting
メソッドによって作成されます。
私の問題は、エラーがOnActionExecuted
方法に存在する場合、私が得る応答があるということである。
[{_Code: -1001, _Description: "Error Description"}]
なぜ私はこれらのアンダースコアを取得し、どのように私はおそらくそれらを取り除くことができますか?