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 string Post (string methodName, String Jsonparas) 2 {3 string strurl = Url + "/" + Me Thodname; 4 5//Create an HTTP request 6 HttpWebRequest request = (HttpWebRequest) webrequest.create (strURL); 7//post Request Method 8 requests. Method = "POST"; 9//Content type request. ContentType = "application/x-www-form-urlencoded"; 11 12//Set parameters and URL code 13//Although we need to pass the actual parameter to the server side is J Sonparas (format: [{\ "userid\": \ "0206001\", \ "username\": \ "Ceshi\"}]), 14//But the string parameter needs to be constructed as a key-value pair (note: "Paramaters=[{\" use             Rid\ ": \" 0206001\ ", \" username\ ": \" Ceshi\ "}]"), 15//Where the key paramaters is the parameter name of the WebService interface function, and the value is a serialized JSON data string 16 Finally, the string parameters are URL-encoded by string paraurlcoded = System.Web.HttpUtility.UrlEncode ("paramaters"); araurlcoded + = "=" + System.Web.HttpUtility.UrlEncode (Jsonparas), byte[] payload;21//JSON character string conversion to byte payload = SyStem. Text.Encoding.UTF8.GetBytes (paraurlcoded); 23//Set the requested ContentLength request. ContentLength = payload. LENGTH;25//Send request, GET request stream writer;28 Try29 { Riter = Request.                 GetRequestStream ();//Gets the stream object used to write the request data}32 catch (Exception) 33 {34 writer = null;35 Console.Write ("Connection server failed!"); 36}37//writes the request parameter to stream-writer. Write (payload, 0, payload. Length);             Close ();//closes the request stream by a string of strvalue = "";//strvalue the character stream returned by the HTTP response HttpWebResponse response;43 TRY44 {45//Get response stream response = (HttpWebResponse) request. GetResponse (),}48 catch (WebException ex), {response = ex. Response as httpwebresponse;51}52-Stream s = responSe.  GetResponseStream (); 54 55//The server side returns an XML-formatted string, and the content of XML is the JSON data we need. XmlTextReader Reader = New XmlTextReader (s); reader.movetocontent (); strvalue = Reader.readinnerxml ();//Remove the content of J Son data Reader.close (); S.close (); strvalue;//return JSON data 63}

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.

Reproduced in: http://www.cnblogs.com/caiwenz/p/3910566.html

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.