0

我正在尝试从旧版 VB 代码中调用 WebAPI2 api。

该 API 在从提琴手或 AngularJS 客户端调用时有效。

[Route("CreateMyObject")]
[HttpPost]
public async Task<JsonResult<MyObject>> CreateMyObject([FromUri] int parentId, [FromBody] MyObject object)

然后在VB代码中:

Dim apiUri As New Uri(apiUrl & "api/CreateMyObject?parentId=" &
intParentId.ToString())
Dim data = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(myObjectInstance))
Dim webRequest As WebRequest = WebRequest.Create(uri)
webRequest.ContentType = "application/json"
webRequest.Method = "POST"

webRequest.ContentLength = data.Length
Dim stream = webRequest.GetRequestStream()
stream.Write(data, 0, data.Length)
stream.Close()

Dim response = webRequest.GetResponse().GetResponseStream()
Dim reader As New StreamReader(response)
Dim res = reader.ReadToEnd()
reader.Close()
response.Close()

我只能从 API 获得 415 响应。我也尝试了其他内容类型,但结果相同或服务器错误。

此调用的任何问题似乎都与 Json 主体位有关,因为如果我不在调用主体中发送任何内容,则 parentId 会按预期到达 API。

4

1 回答 1

0

正如 Chase Rocker 提到的,首先尝试将 jsonDataBytes 初始化为

Dim jsonDataBytes As Bytes()

还要验证 json 对象以确保它正常。使用此链接http://jsonlint.com/或使用Fiddler获得更好的帮助 。

于 2016-04-04T14:37:19.833 回答