Consume webservices from asp.net

1

I have an asp.net C # application (VS 2010), where I have a form with a textbox , a button (to search for records according to ID, and I must pass it as a string to web service ) and a gridview ,

But the data I have to take from a web service REST done in node.js that is on another server in the network.

I'm new to web services so I do not know how to do this.

Help please, suggestions?

    
asked by mulder 29.07.2016 в 15:37
source

1 answer

1

Assuming the service returns JSON , we must follow the steps:

  • Create the RestfUL request URI.
  • Publish URI and get the answer of HttpWebResponse .
  • Converts ResponseStreem to serialized object of function DataContractJsonSerialized .
  • Get the results / particular elements of the serialized object.
  • That's the code in C # something generic

        public static object MakeRequest(string requestUrl, object JSONRequest, string JSONmethod, string JSONContentType, Type JSONResponseType) {  
    
        try {  
            HttpWebRequest request = WebRequest.Create(requestUrl) as HttpWebRequest;  
            //WebRequest WR = WebRequest.Create(requestUrl);   
            string sb = JsonConvert.SerializeObject(JSONRequest);  
            request.Method = JSONmethod;  
            // "POST";request.ContentType = JSONContentType; // "application/json";   
            Byte[] bt = Encoding.UTF8.GetBytes(sb);  
            Stream st = request.GetRequestStream();  
            st.Write(bt, 0, bt.Length);  
            st.Close();  
    
    
            using(HttpWebResponse response = request.GetResponse() as HttpWebResponse) {  
    
                if (response.StatusCode != HttpStatusCode.OK) throw new Exception(String.Format(  
                    "Server error (HTTP {0}: {1}).", response.StatusCode,  
                response.StatusDescription));  
    
                // DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(Response));// object objResponse = JsonConvert.DeserializeObject();Stream stream1 = response.GetResponseStream();   
                StreamReader sr = new StreamReader(stream1);  
                string strsb = sr.ReadToEnd();  
                object objResponse = JsonConvert.DeserializeObject(strsb, JSONResponseType);  
    
                return objResponse;  
            }  
        } catch (Exception e) {  
    
            Console.WriteLine(e.Message);  
            return null;  
        }  
    }  
    
        
    answered by 25.01.2018 в 17:55