Imports System
Imports System.IO
Imports System.Linq
Imports System.Collections.Generic
Imports System.Web.Helpers
Imports System.Web.Mvc
Public Class DynamicJsonAttribute
Inherits CustomModelBinderAttribute
Public Property MatchName As Boolean
Public Overrides Function GetBinder() As System.Web.Mvc.IModelBinder
Return New DynamicJsonBinder(MatchName)
End Function
End Class
Public Class DynamicJsonBinder
Implements IModelBinder
Private ReadOnly matchName As Boolean
Sub New(matchName)
Me.matchName = matchName
End Sub
Public Function BindModel(controllerContext As System.Web.Mvc.ControllerContext, bindingContext As System.Web.Mvc.ModelBindingContext) As Object Implements System.Web.Mvc.IModelBinder.BindModel
Dim contentType = controllerContext.HttpContext.Request.ContentType
If Not contentType.StartsWith("application/json", StringComparison.OrdinalIgnoreCase) Then
Return Nothing
End If
Dim bodyText As String
Using myStream As IO.Stream = controllerContext.HttpContext.Request.InputStream
myStream.Seek(0, SeekOrigin.Begin)
Using myReader As New StreamReader(myStream)
bodyText = myReader.ReadToEnd()
End Using
End Using
If (String.IsNullOrEmpty(bodyText)) Then
Return Nothing
End If
Dim parsed = Json.Decode(bodyText)
If Not matchName Then
Return parsed
End If
Dim members As IEnumerable(Of String) = parsed.GetDynamigMemberNames()
If members Is Nothing OrElse members.Contains(bindingContext.ModelName) Then
Return parsed(bindingContext.ModelName)
End If
Return Nothing
End Function
End Class