【问题标题】:Return Valid Enumeration List in ASP.NET Web API Error Response在 ASP.NET Web API 错误响应中返回有效枚举列表
【发布时间】: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


    【解决方案1】:

    我创建了一个自定义转换器来反序列化枚举。如果转换器无法将 JsonReader 的值解析到目标枚举中,则会引发错误。

    Public Class EnumConverter
        Inherits JsonConverter
        Public Overrides Function CanConvert(objectType As Type) As Boolean
            Return True
        End Function
        Public Overrides Function ReadJson(reader As JsonReader, objectType As Type, existingValue As Object, serializer As JsonSerializer) As Object
            Try
                'if the enum parses properly, deserialize the object like usual
                Dim tryParse As Object = [Enum].Parse(objectType, reader.Value)
                Return serializer.Deserialize(reader, objectType)
            Catch ex As Exception
                'value wasn't valid - return a response stating such and indicating the valid values
                Dim valid As String = String.Format("'{0}'", String.Join(",", [Enum].GetNames(objectType)).Replace(",", "','"))
                Throw New FormatException(String.Format("'{0}' is not a valid value for {1}; Valid values include: {2}", reader.Value, reader.Path, valid))
                Return Nothing
            End Try
        End Function
        Public Overrides Sub WriteJson(writer As JsonWriter, value As Object, serializer As JsonSerializer)
            'use the default serialization
            serializer.Serialize(writer, value)
        End Sub
    End Class
    

    ...

    Public Class MyObject
        <JsonConverter(GetType(EnumConverter))> _
        Public Property MyProp As MyEnum
        Public Enum MyEnum
            Foo
            Bar
        End Enum
    End Class
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-07-09
      • 2018-04-07
      • 2014-11-18
      • 2014-07-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多