使用RestSharp Client将对象列表传递给Web API

时间:2016-08-26 20:40:22

标签: asp.net-mvc-4 asp.net-web-api restsharp

我正在尝试使用以下方法将对象列表从MVC发送到WEBAPI。 API能够从控制器接收列表,但是,API侧的每个项的值都为空/空。 有人可以帮我解决这个问题吗?

控制器方法:

private List<FCM.Models.Facility> GetFacilityDetails()
{
    var url = "http://localhost:64664/";

    var facilies = new List<Facility>();

    facilies.Add( new Facility{ FCLT_ID = 100, FCLT_NM = "Facility 100" });
    facilies.Add( new Facility{ FCLT_ID = 200, FCLT_NM = "Facility 200" });
    facilies.Add( new Facility{ FCLT_ID = 300, FCLT_NM = "Facility 300" });

    var json = JsonConvert.SerializeObject(facilies);

    var _client = new RestClient(url);
    var request = new RestRequest("api/facility/details", Method.GET) { RequestFormat = DataFormat.Json };

    facilies.ForEach(fclt =>
                    request.AddParameter("facilites", fclt, ParameterType.GetOrPost));

    var response = _client.Execute<List<FCM.Models.Facility>>(request);

    if (response.Data == null)
    {
        throw new Exception(response.ErrorMessage);
    }

    return response.Data;
}

WebAPI方法:

[Route("api/facility/details")]
public IEnumerable<Facility> GetFullAddress([FromUri] IEnumerable<Facility> facilities)
{
    return null;
}

1 个答案:

答案 0 :(得分:0)

与建议的评论一样,您可能希望发出POST请求,但如果您希望发送包含GET请求的数组,则可以这样做(使用System.Net.Http.HttpClient }):

Format课程添加Facility方法:

public class Facility
{
    public int FCLT_ID { get; set; }
    public string FCLT_NM { get; set; }

    public string Format(int index)
    {
        return $"[{index}].FCLT_ID={FCLT_ID}&[{index}].FCLT_NM={FCLT_NM}";
    }
}

定义一个可以格式化数组值的类:

public class FacilityList : List<Facility>
{
    public string Format()
    {
        var builder = new StringBuilder();

        for (var i = 0; i < Count; i++)
        {
            builder.Append(this[i].Format(i));

            if(i != Count -1)
            {
                builder.Append("&");
            }
        }

        return builder.ToString();
    }
}

然后发出请求:

var client = new HttpClient()
{
    BaseAddress = new Uri("http://localhost:64664/"),
    DefaultRequestHeaders = {Accept = {new MediaTypeWithQualityHeaderValue("application/json")}}
};

var facilities = new FacilityList
{
    new Facility {FCLT_ID = 100, FCLT_NM = "Facility 100"},
    new Facility {FCLT_ID = 200, FCLT_NM = "Facility 200"},
    new Facility {FCLT_ID = 300, FCLT_NM = "Facility 300"}
};

var format = facilities.Format();

var response = client.GetAsync("api/facility/details?" + format).GetAwaiter().GetResult();

var result = JsonConvert.DeserializeObject<IEnumerable<Facility>>(response.Content.ReadAsStringAsync().GetAwaiter().GetResult());

这将绑定到您的控制器操作:

[Route("api/facility/details")]
public IHttpActionResult Get([FromUri] IEnumerable<Facility> facilities)
{ 
    // Do stuff..
    return Ok(facilities);
}