I'm needing a way to convert a complex web request into .Net objects. I understand that WebAPI uses a default model binder, and that for complicated data, a custom model binder is needed.
Objects
Public Class LapMobileModel
Public Property Type As Integer
Public Property EndTime As String
Public Property StartTime As String
End Class
Public Class RaceMobileModel
Public Property RaceName As String
Public Property UserId As Integer
Public Property Laps As IEnumerable(Of LapMobileModel)
Public Property numberOfRacers As String
Public Property PreRacePosition As String
Public Property PostRacePosition As String
End Class
Public Class RaceListMobileModel
Public Property RaceList As IEnumerable(Of RaceMobileModel)
End Class
Action (in an ApiController)
Public Function SyncLapData(ByVal raceList As RaceListMobileModel) As String
'stuff
Return "OK"
End Function
And I have the skeleton of a custom model binder:
Imports System.Web.Http
Imports System.Web.Http.ModelBinding
Imports System.Web.Http.Controllers
Public Class EventDataModelBinder
Implements IModelBinder
Public Function BindModel(actionContext As HttpActionContext,
bindingContext As ModelBindingContext)
As Boolean Implements IModelBinder.BindModel
End Function
End Class
Questions:
How do I use the actionContext
to get to the data I need to build the RaceListMobileModel
?
How do I properly store it in the bindingContext
?
Right now, the data is being sent via a POST with JSON content.
Web api doesn't use model binding to bind data from request body. You should take a look of parameter binding instead. http://blogs.msdn.com/b/jmstall/archive/2012/05/11/webapi-parameter-binding-under-the-hood.aspx
For the json content, web api uses json.net serializer as default to bind the model. It supports nested models or collections. So I don't see anything unsupported in your models. Did you encounter any issue when deserializing a json? Or you have some special logic when binding the data?