0
當API用戶發送包含無效枚舉的POST請求時,是否有一種很好的方法可以提供包含有效枚舉的更有用的錯誤響應?ASP.NET Web API中的返回有效枚舉錯誤響應
所以,如果我有一個樣本類與枚舉:
Public Class MyObject
Public Property MyProp As MyEnum
Public Enum MyEnum
Foo
Bar
End Enum
End Class
和動作過濾器:
Public Class ValidateModelAttribute
Inherits ActionFilterAttribute
Public Overrides Sub OnActionExecuting(actionContext As HttpActionContext)
If actionContext.ModelState.IsValid = False Then
actionContext.Response = actionContext.Request.CreateErrorResponse(HttpStatusCode.BadRequest, actionContext.ModelState)
End If
End Sub
End Class
如果用戶發送類似:
{
"MyProp": "NotValid"
}
行動過濾器發送錯誤響應,如:
{
"Message": "The request is invalid.",
"ModelState": {
"value.MyProp.MyEnum": [
"Error converting value \"NotValid\" to type 'API.MyObject+MyEnum'. Path 'MyObject.MyEnum', line 29, position 32."
]
}
}
我希望能夠發送一個更有用的錯誤響應,如:
{
"Message": "The request is invalid.",
"ModelState": {
"value.MyProp.MyEnum": [
"'NotValid' is not a valid value for MyProp; Valid values include 'Foo','Bar'"
]
}
}
我如何能勝任這個有什麼想法?