2015-09-15 54 views
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'" 
    ] 
    } 
} 

我如何能胜任这个有什么想法?

回答

0

我创建了一个自定义转换器来反序列化枚举。如果转换器无法将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 
相关问题