【发布时间】:2014-06-10 10:34:13
【问题描述】:
我正在尝试将 json 对象作为发布数据的一部分发送到 Web api。一些 json 值可以是 byte[]。这有可能吗?如果有,怎么做?
这是我的代码:
public static dynamic ExecuteAndReturn(string url, string contentType, string requestType, Dictionary<string, object> parameters)
{
try
{
System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);
string postData = "";
if (contentType.Contains("json"))
postData += "{";
foreach (string key in parameters.Keys)
{
object value = parameters[key];
if (value.GetType() == typeof(bool))
value = value.ToString().ToLower();
else if (value.GetType() == typeof(byte[]))
value = //What to do
if (contentType.Contains("json"))
postData += HttpUtility.UrlEncode(key) + ":" + HttpUtility.UrlEncode(value.ToString()) + ",";
else
postData += HttpUtility.UrlEncode(key) + "=" + HttpUtility.UrlEncode(value.ToString()) + "&";
}
if (contentType.Contains("json"))
{
if (postData.Length > 1)
postData = postData.Substring(0, postData.Length - 1);
postData += "}";
}
byte[] data = Encoding.ASCII.GetBytes(postData);
request.ContentLength = data.Length;
request.ContentType = contentType;
request.Method = requestType;
request.CookieContainer = new System.Net.CookieContainer();
foreach (string key in HttpContext.Current.Request.Cookies)
{
HttpCookie cookie = HttpContext.Current.Request.Cookies[key];
request.CookieContainer.Add(new System.Net.Cookie(cookie.Name, cookie.Value, cookie.Path, new Uri(url).Host));
}
using (var sr = request.GetRequestStream())
{
sr.Write(data, 0, data.Length);
sr.Close();
}
System.Net.WebResponse response = request.GetResponse();
using (var sr = new System.IO.StreamReader(response.GetResponseStream()))
{
string json = sr.ReadToEnd();
System.Text.RegularExpressions.Regex r = new System.Text.RegularExpressions.Regex("\\\"__type\\\":\\\"[a-zA-Z]+[\\.]*[a-zA-Z]+\\\",");
foreach (System.Text.RegularExpressions.Match match in r.Matches(json))
{
json = json.Replace(match.Value, "");
}
return (new JavaScriptSerializer()).Deserialize<dynamic>(json);
}
}
catch (System.Net.WebException exception)
{
System.Net.HttpWebResponse errorResponse = (System.Net.HttpWebResponse)exception.Response;
System.IO.Stream resst = errorResponse.GetResponseStream();
System.IO.StreamReader sr = new System.IO.StreamReader(resst);
string text = sr.ReadToEnd();
return new { Error = text };
}
}
调用函数如下所示:
ExecuteAndReturn(
Objects.SiteContext.Settings["Some_Url"].Value + "/SignOut",
"application/json; charset=UTF-8",
"POST",
new Dictionary<string, object>()
{
{ "userName", someByte[] },
{ "key", anotherByte[] }
});
这里赋值时 byte[] 的值应该是什么:
foreach (string key in parameters.Keys)
{
object value = parameters[key];
if (value.GetType() == typeof(bool))
value = value.ToString().ToLower();
else if (value.GetType() == typeof(byte[]))
value = //this should be the byte[] value, what to do
if (contentType.Contains("json"))
postData += HttpUtility.UrlEncode(key) + ":" + HttpUtility.UrlEncode(value.ToString()) + ",";
else
postData += HttpUtility.UrlEncode(key) + "=" + HttpUtility.UrlEncode(value.ToString()) + "&";
}
【问题讨论】:
-
从客户端发送
byte[]作为编码字符串(例如base64)然后在服务器将其转换回byte[]通常更容易。 -
@James,是的,在理想世界中。在这种情况下,我们正在尝试为所有调用创建一个通用方法,并且无法访问我们遇到问题的 api。
标签: c# json httpwebrequest