无法将对象列表传递给Web API

时间:2016-08-27 01:28:06

标签: c# asp.net-mvc asp.net-web-api restsharp

我在MVC应用程序中使用以下代码

Facility fcl = new Facility();
fcl.AD_LN_1 = "aaaaaa";
fcl.AD_LN_2 = "vbbbbbbbbb";
fcl.CITY_NM = "cccccccccc";
fcl.CTRY_CD_ID = "12";
fcl.CTRY_NM = "ddddddddd";
var fclts = new List<Facility>() { fcl };

var url = ConfigurationManager.AppSettings["FCMWebApi.Facility"].ToString();
var client = new RestClient(url);
var request = new RestRequest("api/facility/fulladdress",Method.GET);         
request.RequestFormat = DataFormat.Json;
request.AddJsonBody(fclts);           
var response = client.Execute<Facility>(request);

但它总是在WEB API端传递null.WEB API代码

public IEnumerable<FCM.Models.Facility>  GetFullAddress(IEnumerable<FCM.Models.Facility> fclt)
{
}

你能建议吗?

2 个答案:

答案 0 :(得分:0)

将此更改为var request = new RestRequest("api/facility/fulladdress",Method.GET);至此var request = new RestRequest("api/facility",Method.POST);

在服务器端,您需要重命名方法名称,即更改如下

public IEnumerable<FCM.Models.Facility>  PostFullAddress(IEnumerable<FCM.Models.Facility> fclt)
{
}

答案 1 :(得分:0)

另一种方法是在字符串中发布并转换它(我将其转换为`所以我也可以使用Get)。

public string Post(string getParams)
{
    getParams = getParams.Replace("`", "\"");
    GetParams getParams2 = JsonConvert.DeserializeObject<GetParams>(getParams);

在客户端:

            // "Post" method.
            using (var client = new HttpClient(new HttpClientHandler()
            {
                UseDefaultCredentials = true
            }))
            {
                string url = StaticVars.WebAPIURL + "WebAPIRequest/";
                var content = new FormUrlEncodedContent(new[]
                {
                    new KeyValuePair<string, string>("getParams", getParams),
                    });
                HttpResponseMessage responseMessage = new HttpResponseMessage();
                Task task = Task.Run(async () =>
                {
                    responseMessage = await client.PostAsync(url, content);
                    var contents = await responseMessage.Content.ReadAsStringAsync();
                    response = contents.ToString();
                    if (response != "Failed")
                    {
                        importedFiles = JsonConvert.DeserializeObject<List<ImportedFile>>(response);
                    }

                });
                task.Wait();