Posts

....
Technical Blog for .NET Developers ©

Saturday, January 28, 2017

Json RPC Requests

Json RPC is becoming an extended messaging system as it is adjusted to most of actual web scenarios

Nugets for json de-serialization implement the structures to parametrize the request, we are adding Newtonsoft libraries



The method to invoke is in server side gurujsonrpc.appsoft.com, requires id and one param, and its response is a json structure with version, id, and result

The request class exposes one method returning the raw WebResponse of the invocation


    public class JsonRPCClient : HttpWebClientProtocol
    {
        public string MethodVerb { get; set; }

        public string Version { get; set; }

        public string Id { get; set; }

        public string InvokeUrl { get; set; }

        public string MethodName { get; set; }

        public object ParamsElements { get; set; }


        public WebResponse Invoke()
        {
            HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(InvokeUrl);

            webRequest.ContentType = "application/json-rpc";
            webRequest.Method = MethodVerb;

            JObject message = new JObject();
            message.Add(new JProperty("jsonrpc", Version));
            message.Add(new JProperty("id", Id));
            message.Add(new JProperty("method", MethodName));

            if (ParamsElements != null)
            {
                object[] _params = new [] { ParamsElements };

                JArray _elements = new JArray();
                _elements.Add(_params);

                message.Add(new JProperty("params", _elements));
            }

            string s = JsonConvert.SerializeObject(message);
            byte[] byteArray = Encoding.UTF8.GetBytes(s);
            webRequest.ContentLength = byteArray.Length;
            Stream dataStream = webRequest.GetRequestStream();
            dataStream.Write(byteArray, 0, byteArray.Length);
            dataStream.Close();

            WebResponse webResponse = webRequest.GetResponse();

            return webResponse;
        }

    }


The method response returns the json object with the results


            var client = new JsonRPCClient
                {
                    InvokeUrl = "https://gurujsonrpc.appspot.com/guru",
                    MethodName = "guru.test",
                    MethodVerb = "POST",
                    Version = "2.0",
                    Id = "123",
                    ParamsElements = "Guru"
                };

            var response = client.Invoke();

            Stream responseStream = response.GetResponseStream();

            StreamReader reader = new StreamReader(responseStream);

            string result = reader.ReadToEnd();