有什么方法可以通过WebClient发送IEnumerable <t>作为参数吗?

时间:2019-01-22 23:04:15

标签: c# webclient

我想发送一个IEnumerable<T>和一些其他属性作为参数,以从API调用HttpGet,我的控制器如下所示:

[HttpGet]
public Task<IEnumerable<string>> Get([FromQuery] Foo foo) //Notice [FromQuery]
{
    //some stuff here that returns an IEnumerable of strings
}  

Foo的结构是:

public class Foo 
{
    public IEnumerable<Guid> Guids { get; set; }
    public DateTime BeginDate { get; set; }
    public DateTime EndDate { get; set; }
}

和我的WebClient逻辑需要动态命中不同的端点并为请求创建参数,这是我到目前为止所做的:

public class WebClientRequestClass
{
    public T Get<T>(string url, object args = null)
    {
        using (var webClient = new WebClient())
        {
            webClient.BaseAddress = @"http://localhost:(SomePortGoesHere)/api/";
            webClient.QueryString = ToQueryString(args);
            var json = webClient.DownloadString(@"SomeEndpointGoesHere");

            var javaScriptSerializer = new JavaScriptSerializer();
            javaScriptSerializer.MaxJsonLength = Int32.MaxValue;
            return (T)javaScriptSerializer.Deserialize(json, typeof(T));
        }
    }

    private NameValueCollection ToQueryString(object args)
    {       
        var pairs = args
               .GetType()
               .GetProperties(BindingFlags.Public | BindingFlags.Instance)
               .Select(p =>
               {
                   var value = p.GetValue(args, null);
                   if (value is DateTime)
                   {
                       return new KeyValuePair<string, string>(p.Name, Encode(((DateTime)value).ToString("yyyy-MM-dd")));
                   }
                   else
                   {
                       return new KeyValuePair<string, string>(p.Name, Encode(value.ToString())); //Problem goes here for objects and ToString() implementation

                   }
               });

        var nameValueCollection = new NameValueCollection();
        foreach (var pair in pairs)
        {
            nameValueCollection.Add(pair.Key, pair.Value);
        }
        return nameValueCollection;
    }
}

所以我的问题是我的收藏集未得到正确处理,我的Uri看起来像 http://localhost:666/api/EndPoint?Guids=System.Guid[]&BeginDate=2018-01-22&EndDate=2019-01-22

注意 Guids = System.Guid [] ,而不是我的集合值,如何解决此问题?

也许是ToString()Foo的自定义实现?是在控制器中更改[FromQuery]

0 个答案:

没有答案