http calls webservice to operate on the httprequest httpresponse example

  • 2020-12-09 00:48:54
  • OfStack

REST WCF makes it easy to call Web services through HttpRequest interactions. So can the old WebService do it? In WebService, HttpContext. Current. Rquest/Response, we can also transform WebMethod with one sample.

Client:


//  create 1 a DataTable   
DataTable data = new DataTable("Project");  
data.Columns.Add("Name");  
data.Columns.Add("Birthday");  
data.Rows.Add(new object[] { "Wendy", "1978/03/11" });  
data.Rows.Add(new object[] { "Philip", "2000/11/05" });  
data.Rows.Add(new object[] { "Felix", "1999/08/04" });  
using (var ms = new MemoryStream())  
{  
    //  will DataTable with Xml Format write to stream    
    data.WriteXml(ms, XmlWriteMode.WriteSchema);  
    var client = new WebClient();  
    //  define HttpRequest the Content-Type(xml,json Etc. )   
    client.Headers.Add("Content-Type", "text/xml");  
    var url = "http://localhost:2609/Service1.asmx/SendXml";  
    // Send HttpRequest   
    var resp = client.UploadData(url, "POST", ms.ToArray());  
    var strResp = System.Text.Encoding.UTF8.GetString(resp);  
    MessageBox.Show(strResp);  
}

Server:


[WebMethod]  
public void SendXml()  
{  
    //  Get the client RAW HttpRequest   
    var inputStream = HttpContext.Current.Request.InputStream;  
    //  define Response The format returned is :Json   
    var response = HttpContext.Current.Response;  
    response.ContentType = "text/json";  
    //var strXml = "";   
    //using (var sr = new StreamReader(inputStream))   
    //    strXml = sr.ReadToEnd();   
    try  
    {  
        DataTable data = new DataTable();  
        using (var xr = XmlReader.Create(inputStream))  
            data.ReadXml(xr);  
        //  Will be read in Xml the DataTable The number of rows returned to the client    
        string count = "/"" + data.Rows.Count + "/"";  
        response.BinaryWrite(System.Text.Encoding.UTF8.GetBytes(count));  
    }  
    catch (Exception ex)  
    {  
        response.BinaryWrite(System.Text.Encoding.UTF8.GetBytes(ex.Message));  
    }  
}

Client output ""3""

PS: If the client's HttpRequest satisfies the SOAP serialization format, WebService deserializes the message into a parameter for WebMethod. The corresponding client proxy class is also used by the client by deserializing messages into objects.


Related articles: