将JSON对象转换为查询字符串并附加到GET URL的最佳方法是什么?POST是直接的,并由我的Web API后端读取。
{Name:'迈克' } =?姓名=迈克
private static string MakeRequest(HttpWebRequest req, string data)
{
try
{
if (req.Method == Verbs.POST.ToString() || req.Method == Verbs.PUT.ToString() || req.Method == Verbs.DELETE.ToString())
{
var encodedData = Encoding.UTF8.GetBytes(data);
req.ContentLength = encodedData.Length;
req.ContentType = "application/json";
req.GetRequestStream().Write(encodedData, 0, encodedData.Length);
}
using (var response = req.GetResponse() as HttpWebResponse)
using (var reader = new StreamReader(response.GetResponseStream()))
{
return reader.ReadToEnd();
}
}
catch (WebException we)
{
if(we.Response == null)
{
return JsonConvert.SerializeObject(new { Errors = new List<ApiError> { new ApiError(11, "API is currently unavailable") }});
}
using (var response = we.Response as HttpWebResponse)
using (var reader = new StreamReader(response.GetResponseStream()))
{
return reader.ReadToEnd();
}
}
}
4条答案
按热度按时间yhxst69z1#
如果json对象是平面的,如示例中所示,则
查询将为
name=charlie&num=123
kognpnkq2#
我让这段代码运行在. Net核心:
示例:
qeeaahzv3#
试试这个,在深
要用途:某个对象.GetQueryString();
8fsztsew4#
如果您对象(实体)具有类似于此实体的子实体:
您可以使用此代码进行构建查询:首先将实体模型转换为JObject并调用此方法:
你可以得到像这样的查询字符串: