gpt4 book ai didi

jquery - .NET 相当于 JQuery.param()

转载 作者:行者123 更新时间:2023-12-01 01:07:06 25 4
gpt4 key购买 nike

我想改进我的 Web API 测试并寻找一种更好地格式化 URL 的方法。

var filter = new {
State = new[] {"A", "C"},
MaxAge = 60,
POI = new { Lat = 40, Long = -130 }
};

我应该调用什么来将查询字符串格式化为 JQuery.param()函数有什么作用?

最佳答案

There您可以找到一个扩展方法,它可以帮助您将对象转换为查询字符串

public static class UrlHelpers
{
public static string ToQueryString(this object request, string separator = ",")
{
if (request == null)
throw new ArgumentNullException("request");

// Get all properties on the object
var properties = request.GetType().GetProperties()
.Where(x => x.CanRead)
.Where(x => x.GetValue(request, null) != null)
.ToDictionary(x => x.Name, x => x.GetValue(request, null));

// Get names for all IEnumerable properties (excl. string)
var propertyNames = properties
.Where(x => !(x.Value is string) && x.Value is IEnumerable)
.Select(x => x.Key)
.ToList();

// Concat all IEnumerable properties into a comma separated string
foreach (var key in propertyNames)
{
var valueType = properties[key].GetType();
var valueElemType = valueType.IsGenericType
? valueType.GetGenericArguments()[0]
: valueType.GetElementType();
if (valueElemType.IsPrimitive || valueElemType == typeof (string))
{
var enumerable = properties[key] as IEnumerable;
properties[key] = string.Join(separator, enumerable.Cast<object>());
}
}

// Concat all key/value pairs into a string separated by ampersand
return string.Join("&", properties
.Select(x => string.Concat(
Uri.EscapeDataString(x.Key), "=",
Uri.EscapeDataString(x.Value.ToString()))));
}
}

并将其用作string querystring = example.ToQueryString();

关于jquery - .NET 相当于 JQuery.param(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27088663/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com