【问题标题】:Receiving complex data via WebAPI action通过 WebAPI 操作接收复杂数据
【发布时间】:2012-11-15 07:38:05
【问题描述】:

我需要一种将复杂的 Web 请求转换为 .Net 对象的方法。我了解 WebAPI 使用默认模型绑定器,对于复杂的数据,需要自定义模型绑定器。

对象

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

动作(在 ApiController 中)

Public Function SyncLapData(ByVal raceList As RaceListMobileModel) As String
    'stuff
    Return "OK"
End Function

我有一个自定义模型绑定器的骨架:

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

问题:

如何使用actionContext 获取构建RaceListMobileModel 所需的数据?

如何将其正确存储在bindingContext 中?

现在,数据正在通过带有 JSON 内容的 POST 发送。

【问题讨论】:

    标签: vb.net asp.net-web-api custom-model-binder


    【解决方案1】:

    Web api 不使用模型绑定来绑定请求正文中的数据。你应该看看参数绑定。 http://blogs.msdn.com/b/jmstall/archive/2012/05/11/webapi-parameter-binding-under-the-hood.aspx

    对于 json 内容,web api 默认使用 json.net 序列化器来绑定模型。它支持嵌套模型或集合。所以我没有看到你的模型中有任何不支持的东西。你在反序列化 json 时遇到过什么问题吗?或者你在绑定数据的时候有什么特殊的逻辑?

    【讨论】:

    • 加油!我期待一个从未出现过的问题!非常感谢!反序列化工作正常。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多