【发布时间】:2015-09-16 22:50:31
【问题描述】:
当 API 用户发送包含无效枚举的 POST 请求时,是否有一种好方法可以提供包含有效枚举的更有用的错误响应?
如果我有一个带有枚举器的示例类:
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'"
]
}
}
有什么想法可以解决这个问题吗?
【问题讨论】:
标签: asp.net vb.net asp.net-web-api