Web Service-based client framework build one: C # invokes a Web service using the HTTP POST method to pass a JSON data string

Source: Internet
Author: User
Tags http post object serialization urlencode

Introduction

The previous time has been doing an ERP system, as the system functions, the client (CS mode) becomes more and more bloated. Now you want to separate the following parts of the business logic layer from the interface layer, using a Web service. Because the method of calling Web service in C # by directly adding a reference to towners is not flexible enough, a Web service is invoked in a way that sends an HTTP request manually. Finally, you choose to use Post to invoke the Web Service, as far as security and efficiency are concerned. In learning to use the process, encountered a lot of problems, also took a long time to solve, online related posts are very few, if you have some problems in the use of the process is difficult to solve, you can find me oh.

Premise

Using the Post method to invoke the Web service, you need to add a configuration using the HTTP protocol in the Service Project Profile Web. config, adding <webServices> < in the <system.web> tab protocols> <add name= "HttpPost"/></protocols></webservices> configuration, we can also add <customerrors mode = "Off"/> configuration, so that the return value of the service method can be taken out of the service method call exception information, the exception information is also returned as XML, so that the client for debugging purposes.

Web Service Interface Methods

[WebMethod]
public string Project (string paramaters)
{
return paramaters;
}

Implementation code

1         Public stringPost (stringMethodName,stringJsonparas)2         {3             stringstrURL = Url +"/"+MethodName;4 5             //Create an HTTP request6HttpWebRequest request =(HttpWebRequest) webrequest.create (strURL);7             //POST Request Mode8Request. Method ="POST";9             //Content TypeTenRequest. ContentType ="application/x-www-form-urlencoded"; One  A             //setting parameters and URL encoding -             //Although the actual parameters that we need to pass to the server side are Jsonparas (format: [{\ "userid\": \ "0206001\", \ "username\": \ "Ceshi\"}]), -             //However, the string parameter needs to be constructed in the form of a key-value pair (note: "Paramaters=[{\" userid\ ": \" 0206001\ ", \" username\ ": \" Ceshi\ "}]"), the             //where the key paramaters is the parameter name of the WebService interface function, and the value is a serialized JSON data string -             //Finally, the string parameter is URL-encoded -             stringparaurlcoded = System.Web.HttpUtility.UrlEncode ("paramaters"); -paraurlcoded + ="="+System.Web.HttpUtility.UrlEncode (Jsonparas); +  -             byte[] payload; +             //Convert a JSON string to a byte APayload =System.Text.Encoding.UTF8.GetBytes (paraurlcoded); at             //set the contentlength of the request -Request. ContentLength =payload. Length; -             //send request, GET request stream -  - Stream writer; -             Try in             { -writer = Request. GetRequestStream ();//gets the stream object used to write the request data to             } +             Catch(Exception) -             { thewriter =NULL; *Console.Write ("failed to connect to the server!"); $             }Panax Notoginseng             //Write request parameters to stream -Writer. Write (Payload,0, payload. Length); theWriter. Close ();//close the request flow +  AString strvalue ="";//strvalue The character stream returned by the HTTP response the HttpWebResponse response; +             Try -             { $                 //get the response stream $Response =(HttpWebResponse) request. GetResponse (); -             } -             Catch(WebException ex) the             { -Response = ex. Response asHttpWebResponse;Wuyi             } the  -Stream s =Response. GetResponseStream (); Wu  -             //The server side returns an XML-formatted string, and the XML content is the JSON data we need AboutXmlTextReader Reader =NewXmlTextReader (s); $ reader.movetocontent (); -strvalue = Reader.readinnerxml ();//extracting JSON data from the content - reader.close (); - s.close (); A  +             returnstrvalue;//return JSON data the}

URL format sample: "Http://59.68.29.106:8087/IFT_Project.asmx"

The methodname parameter is "Project"

Jsonparas is the value that is obtained after serializing an object of type list<object> using C # javascriptserializer, data format: [{\ "userid\": \ "0206001\", \ "username\ ": \" Ceshi\ "the brackets in the}],json data represent the serialization of multiple object collections, the curly braces represent the result of an object serialization, the contents of the curly braces are represented by a key-value pair, the multiple attributes are separated by commas, and each object is separated by commas.

Request. ContentType must set the value, it is recommended to use "application/x-www-form-urlencoded", set other values is very easy to report the server internal exception, using this way the Service interface method returns an XML-formatted string

Payload the request parameter to the binary to save, it is necessary to add "paramaters" in it, otherwise it will report the exception is missing parameters, Paramaters is the service interface function parameter name. URL encoding is used in the function, note that you only need to encode the key and value at the time of encoding, do not encode the middle =, otherwise the GetResponse will report an exception.

Request. ContentLength is also a value that must be set

Stream s = response after getting the response stream. GetResponseStream (); Need to use reader to parse the response stream, this place I am using XmlTextReader, because my service method returns a string in XML format, where the JSON data is in the content of the XML. After the JSON data is removed, the object can be obtained by the corresponding deserialization.

Summary

In the process of learning to use the post call method, see some of the posts, but there are few posts online, many posts also give a sample of the Post method, given a lot of post methods do not explicitly give the format of the incoming string, Cause my incoming parameter Jsonparas missing key paramaters, test debugging for a long time to find this error, eventually almost gave up. There are also contenttype settings that are important, and the requirement for incoming parameters is high with other values, and beginners are not recommended to use other methods. Early use of the post mode, in GetResponse () easy to report the exception, you can set Customererrors mode to return the exception information to the client, so easy to debug.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.