0

I am trying to send a json object as part of post data to a web api. Some of the json values can be byte[]. Is this at all posiible? If so, how?

Here is my code:

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 };
        }
    }

Calling the function looks like this:

ExecuteAndReturn(
            Objects.SiteContext.Settings["Some_Url"].Value + "/SignOut",
            "application/json; charset=UTF-8",
            "POST",
            new Dictionary<string, object>()
            {
                { "userName", someByte[] },
                { "key", anotherByte[] }
            });

What should the byte[] value be when assigning it here:

 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()) + "&";
            }
2
  • 4
    It's generally easier to just send your byte[] as an encoded string (e.g. base64) from the client and then convert it back to a byte[] at the server. Commented Jun 10, 2014 at 10:36
  • 1
    @James, yes, in an ideal world. In this case we are trying to create a generic method for all our calls and don't have access to the api that we are having trouble with. Commented Jun 10, 2014 at 10:42

1 Answer 1

1

If you are unable to encode to a normal string and decode it on the server end, try a string with json formatting.

    byte[] value = new byte[] { 255, 255, 255, 255 };
    string strValue = "[ ";
    for (int i = 0; i < value.Length; i++)
        strValue += (i == 0 ? "" : ", ") + value[i].ToString();
    strValue += " ]";

    // strValue == "[ 255, 255, 255, 255 ]"
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.