Not able to pass list of object to Web API

丶灬走出姿态 提交于 2019-12-12 05:23:07

问题


I am using below code in MVC application

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

But it is always passing null at WEB API side.. WEB API Code

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

Can you please suggest something ?


回答1:


Change this to var request = new RestRequest("api/facility/fulladdress",Method.GET); to this var request = new RestRequest("api/facility",Method.POST);

On the Server side you need to rename your Method name i.e. change as below

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



回答2:


Another way to do it is to post in a string and convert it (I convert ' to ` so I can use Get as well).

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

And on the client side:

            // "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();


来源:https://stackoverflow.com/questions/39176626/not-able-to-pass-list-of-object-to-web-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!