通过 Rest API 客户端将 LIST 对象传递到 Web API 2 使用 JSON
Pass LIST object by Rest API Client to Web API 2 using JSON
我在将数据列表从客户端传递到 Web API 2 时遇到问题 JSON。
这是我的代码示例
客户端
string RestUrl = "http://***SrviceUrl***/api/InvoiceHeader/{0}";
var uri = new Uri(string.Format(RestUrl, string.Empty));
List<InvItem> myList = new List<InvItem>(Common.invitems);
var json = JsonConvert.SerializeObject(myList);
var content = new StringContent(json, Encoding.UTF8, "application/json");
HttpResponseMessage response = null;
response = await client.PutAsync(uri ,content);
if (response.IsSuccessStatusCode)
{
Debug.WriteLine(@"successfully saved.");
}
Web 服务 - 控制器 class
[HttpPut]
[BasicAuthentication(RequireSsl = false)]
public HttpResponseMessage Put(string item)
{
List<InvItemToSave> myList = new List<InvItemToSave>();
myList = JsonConvert.DeserializeObject<List<InvItemToSave>>(item);
try
{
todoService.InsertInvoiceDetail(myList);
}
catch (Exception)
{
return base.BuildErrorResult(HttpStatusCode.BadRequest, ErrorCode.CouldNotCreateItem.ToString());
}
return base.BuildSuccessResult(HttpStatusCode.Created);
}
当我尝试将单个数据对象传递给同一个控制器时,它工作正常。
但对于 LIST 对象,它是 returns 错误代码。
StatusCode: 405, ReasonPhrase: 'Method Not Allowed'
我试图通过第三方 REST client 传递完全相同的*列表内容*。它返回了成功代码。
您正在将 PutAsync
转化为 HttpPost
动作。您的 api URL 看起来也不正确,应该是
http://***SrviceUrl***/api/InvoiceHeader
行动应该是,
public HttpResponseMessage Put(List<InvItem> items)
我在将数据列表从客户端传递到 Web API 2 时遇到问题 JSON。 这是我的代码示例
客户端
string RestUrl = "http://***SrviceUrl***/api/InvoiceHeader/{0}";
var uri = new Uri(string.Format(RestUrl, string.Empty));
List<InvItem> myList = new List<InvItem>(Common.invitems);
var json = JsonConvert.SerializeObject(myList);
var content = new StringContent(json, Encoding.UTF8, "application/json");
HttpResponseMessage response = null;
response = await client.PutAsync(uri ,content);
if (response.IsSuccessStatusCode)
{
Debug.WriteLine(@"successfully saved.");
}
Web 服务 - 控制器 class
[HttpPut]
[BasicAuthentication(RequireSsl = false)]
public HttpResponseMessage Put(string item)
{
List<InvItemToSave> myList = new List<InvItemToSave>();
myList = JsonConvert.DeserializeObject<List<InvItemToSave>>(item);
try
{
todoService.InsertInvoiceDetail(myList);
}
catch (Exception)
{
return base.BuildErrorResult(HttpStatusCode.BadRequest, ErrorCode.CouldNotCreateItem.ToString());
}
return base.BuildSuccessResult(HttpStatusCode.Created);
}
当我尝试将单个数据对象传递给同一个控制器时,它工作正常。 但对于 LIST 对象,它是 returns 错误代码。
StatusCode: 405, ReasonPhrase: 'Method Not Allowed'
我试图通过第三方 REST client 传递完全相同的*列表内容*。它返回了成功代码。
您正在将 PutAsync
转化为 HttpPost
动作。您的 api URL 看起来也不正确,应该是
http://***SrviceUrl***/api/InvoiceHeader
行动应该是,
public HttpResponseMessage Put(List<InvItem> items)