Webapi以特定格式

时间:2018-06-14 02:54:45

标签: c# arrays asp.net-web-api c#-4.0 query-string

有人能告诉我是否有以下列格式格式化输出的内置方式?我以前没碰过这个。我可以写一个格式化程序,但如果我没有那个是加号。

删除/散装apiKey = 8ea7c969eff8ab3819b9090d225c8625a0d2668d&安培; listCrmId [0] = 30871295&安培; listCrmId 1 = 30871296

我的实体如下

public class BulkDelete
{
    [JsonProperty(PropertyName = "apiKey")]
    public string ApiKey { get; set; }
    [JsonProperty(PropertyName = "listCrmId")]
    public int[] ListCrmId { get; set; }

}

发布我的解决方案,以便其他人可以使用。我发现没有解决方案会按名称[postion] = value输出Array Collection,所以我从here修改了另一个扩展方法。

    public static string GetQueryStringFromArray(this object obj)
    {
        var result = new List<string>();
        var props = obj.GetType().GetProperties().Where(p => p.GetValue(obj, null) != null);
        foreach (var p in props)
        {
            var value = p.GetValue(obj, null);
            switch (value)
            {
                case ICollection enumerable when p.PropertyType.IsArray:
                    var sd = enumerable.Cast<object>();
                    for (int i = 0; i < sd.Count(); i++)
                    {
                        result.Add($"{p.Name}[{i}]={HttpUtility.UrlEncode(sd.ElementAt(i).ToString())}");
                    }
                    break;
                case ICollection enumerable:
                    result.AddRange(enumerable.Cast<object>().Select(v => $"{p.Name}={HttpUtility.UrlEncode(v.ToString())}"));
                    break;
                default:
                    result.Add($"{p.Name}={HttpUtility.UrlEncode(value.ToString())}");
                    break;
            }
        }

        return string.Join("&", result.ToArray());
    }

输出返回 ApiKey = a415ae8151957de117869389aa3e30c068b7eaa5&安培; ListCrmId [0] = 123450&安培; ListCrmId 1 = 123451&安培; ListCrmId [2] = 123452&安培; ListCrmId [3] = 123453&安培; ListCrmId [4] = 123454&安培; ListCrmId [5] = 123455&安培; ListCrmId [ 6] = 123456&安培; ListCrmId [7] = 123457&安培; ListCrmId [8] = 123458&安培; ListCrmId [9] = 123459&安培; ListCrmId [10] = 1234510&安培; ListCrmId [11] = 1234511&安培; ListCrmId [12] = 1234512&安培; ListCrmId [13 ] = 1234513&安培; ListCrmId [14] = 1234514&安培; ListCrmId [15] = 1234515&安培; ListCrmId [16] = 1234516&安培; ListCrmId [17] = 1234517&安培; ListCrmId [18] = 1234518&安培; ListCrmId [19] = 1234519

谢谢@John

0 个答案:

没有答案