简体   繁体   English

使用JSON将Rest API客户端的LIST对象传递给Web API 2

[英]Pass LIST object by Rest API Client to Web API 2 using JSON

I have a problem in pass data list from Client to the Web API 2 by JSON. 我在通过JSON将数据从客户端传递到Web API 2时遇到问题。 Here are my code samples 这是我的代码示例

Client 客户

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 Service - Controller class Web服务-控制器类

    [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);
    }

when i try to pass single data object to same controller it works fine. 当我尝试将单个数据对象传递到同一控制器时,它可以正常工作。 but for LIST objects it returns error code. 但是对于LIST对象,它返回错误代码。

StatusCode: 405, ReasonPhrase: 'Method Not Allowed' StatusCode:405,ReasonPhrase:“不允许使用方法”

I tried to pass exact same * list content* through third party REST client . 我试图通过第三方REST客户端传递完全相同的*列表内容*。 It returned success code. 它返回成功代码。

You are doing a PutAsync into a HttpPost action. 您正在将PutAsync放入HttpPost操作中。 Your api URL looks incorrect as well, should be, 您的api URL看起来也不正确,应该是,

http://***SrviceUrl***/api/InvoiceHeader

and action should be, 行动应该是

public HttpResponseMessage Put(List<InvItem> items)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM