将 JSON 对象转换为查询字符串以附加到 GET Url 的最佳方法是什么?POST 很简单,可以被我的 Web API 后端读取。
{姓名:“迈克”} = ?姓名=迈克
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();
}
}
}