我正在使用vb.net web api 2开发restful web服务,我正在尝试从正文传递参数来执行我的存储过程,
{
"id": "2016",
"Type":"1",
"Year": "1"
}
这是我从正文传递的数据,这里是错误
{“message”:“System.InvalidCastException:从类型转换 键入'String'的'JObject'无效。\ r \ n at Microsoft.VisualBasic.CompilerServices.Conversions.ToString(对象 价值)\ r \ n at WebApplication7.Controllers.SubjectsController.getSubjects(对象 数据)在C:\ Users \ Junaida \ documents \ visual studio中 2015年\项目\ WebApplication7 \ WebApplication7 \控制器\ SubjectsController.vb:行 30“}
我的vb代码:
<HttpPost>
Function getSubjects(<FromBody> ByVal data As Object) As IHttpActionResult
Try
Using entities As IAPD_DBEntities = New IAPD_DBEntities()
Dim year, type, id As String
Dim dictionary = JsonConvert.DeserializeObject(data) 'As Dictionary(Of String, String)
Dim startno As Integer = 0
If year = 1 Then
startno = 0
ElseIf year = 2 And type = 1 Then
startno = 366
ElseIf year = 2 And type = 3 Then
startno = 52
ElseIf year = 2 And type = 2 Then
startno = 13
End If
dictionary.Add("id", id)
dictionary.Add("Type", type)
dictionary.Add("Year", year)
Return Ok(entities.SP_Messages_GetinfoArchive_ByID(startno, id, type, year).ToList)
End Using
Catch e As Exception
Return BadRequest(e.ToString)
End Try
End Function
End Class
答案 0 :(得分:0)
我认为您的data
对象已经是JObject
,而JsonConvert.DeserializeObject
期待一个字符串。您应该能够在不反序列化的情况下访问其属性,如下所示:
dictionary.add("id", data("id").ToString())
dictionary.add("Type", data("Type").ToString())
dictionary.add("Year", data("Year").ToString())
它应该有用。
答案 1 :(得分:0)
您需要创建一个具有与传入JSON结构字段匹配的属性的类,然后MVC Web API将为您进行解析!无需自行反序列化。
示例类:
Public Class SubjectParams
Public Property id As String
Public Property type As String
Public Property year As String
End Class
然后像这样使用它:
<HttpPost>
Function getSubjects(<FromBody> ByVal data As SubjectParams) As IHttpActionResult
然后,您可以使用data.id
,data.type
等
如果你需要属性是其他类型的,那么就这样做(特别是Integer
似乎对至少某些属性有意义。)