2015-09-15 68 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 
相關問題