". Net deep Breathing" chat WCF service returns XML or JSON-formatted data

Source: Internet
Author: User

Sometimes, in order for data to "cross-border", especially the HTTP web-related stuff, the data content will be returned in XML or JSON format, so that whether the client platform is the four ancient civilizations, or in the primitive tribes in the age of barbarism, can use this data.

Implemented in WCF to return data in XML or JSON format there are several Y methods, no matter what method you use, as long as you get the expected results, MI Fu said, the pen can be eight side out of the front, of course, people are referring to painting.

Here, the old week to pick two methods to demonstrate, for reference only, no archaeological value, it is recommended that Sima long do not put this article income "Shiji".

The first approach is to use the Webservicehost class, which automates some configuration related to HTTP communication, but with this class, you run as an administrative identity, or you do not have permission to listen.

First define a book class, and later we will return a book instance as XML or JSON data.

     Public Sealed class Book    {        publicstringgetset;}          Public decimal Get Set ; }          Public string Get Set ; }    }

Then, an important step is to declare the service contract, which is an interface that can be exposed to the client, and of course the client can be redefined.

    [ServiceContract]    interface  iservice    {        [OperationContract]          "Getdata?f={format}")]        Message GetXml (string  format);    

Plus the ServiceContract attribute indicates that it is a service contract, and if name is not explicitly specified, its name is the same as the name of the interface, and the method that you want to expose to the client is added with the OperationContract attribute in the contract interface, otherwise it will not be considered a service operation. cannot be used by clients.

The service contract interface allows different definitions to be used on both the server and the client, as long as the contract has the same name and the method has the same parameter and return value type and number.

The WebGet attribute specifies how the URI should be used, with the address relative to the path, and if the base address is http://dog.net/, the path to the Getxml method is http://dog.net/getdata?f=xml. Originally I just want to return XML data, so called Getxml, and then a thought, the single return XML format content is too stingy, simply get a parameter, to specify the format, you can pass in XML or JSON. The {format} after F will automatically pass the value to the format parameter of the method, so the parameter name of UriTemplate is not wrong, and if it is written as F={firmat}, it will not be able to identify the parameters.

Then to implement the service, the type that implements the contract interface does not have to be exposed to the client because it is executed on the server.

     Public classMyservice:iservice { PublicMessage GetXml (stringformat) {Weboperationcontext Context=weboperationcontext.current; Book B=NewBook {bookname="selling girls ' little matches", Price=25.2M, BarCode="2811365801"            }; Message Msgreturn=NULL; //Judging Format            if(format. ToLower () = ="XML") {Msgreturn= Context. Createxmlresponse<book>(b); }            Else{Msgreturn= Context. Createjsonresponse<book>(b); }            returnMsgreturn; }    }

This is done in a fun way, so the method return type is message. The static property weboperationcontext.current can get the context object associated with the currently invoked operation contract, which is the Weboperationcontext instance. It exposes a bunch of methods, the name is Createxxxresponse, where xxx is what depends on the return content, to return to JSON, call the Createjsonresponse method, return XML call Createxmlresponse method.

Once the book object is instantiated, it can be passed to the Createjsonresponse or Createxmlresponse method with the generic parameter, the type parameter T is specified as book, the book object is automatically serialized, and then returned to the client.

Finally, in the configuration file to set a base address for the service, you can write in the code, you can also write in the configuration file, where the old weeks to choose the configuration file, the advantage is that you can dynamically modify the application without recompiling.

  <System.ServiceModel>    <Services>      <Servicename= "Getxmlsample.myservice">        <Host>          <baseaddresses>            <Addbaseaddress= "http://localhost:1888/"/>          </baseaddresses>        </Host>      </Service>    </Services>  </System.ServiceModel>

May have a beginner's friend said that the WCF configuration file is difficult to write, in fact, Ah, is a regular, you may wish to study carefully, after mastering the rules you will find that the configuration file is not difficult to write.

The value of the service's Name property is the first name (type name, with namespace name) of the type of the Services class.

Instantiate the Webservicehost in main.

        Static void Main (string[] args)        {            new webservicehost (typeof(MyService));            Host. Open ();            Console.WriteLine (" service is turned on. ");            Console.read ();            Host. Close ();        }

Note that the type passed to the constructor is the kind of the service class, which is the same as the value Service/name in the configuration file.

Run this example as Administrator, then open the browser, enter Http://localhost:1888/getdata?f=xml, and you will see something like this:

Change the XML to JSON and see.

What's the fun? The following old week demonstrates another method.

Instead of using Webservicehost, this method uses the normal ServiceHost class to host the service, which can be supported by the HTTP interaction through WebHttpBinding, but don't forget to configure the WebHttpBehavior behavior for the endpoint.

Similarly, a class is defined first and then used for testing.

[DataContract (Namespace ="Http://sample", Name ="Student")]     Public Sealed classStudent {[DataMember (Name="stu_id")]         Public intStuid {Get;Set; } [DataMember (Name="Stu_name")]         Public stringStuname {Get;Set; } }

This time, let's generate the data in XML or JSON serialization and go back to the string. The service contract is as follows:

    [ServiceContract]    publicinterface  IData    {        [OperationContract]         " Getdata?f={format} " )]        string GetData (string  format);    }

Similar to the previous, except that the return type is changed to string.

The following code implements the contract interface:

     Public classMyservice:idata { Public stringGetData (stringformat) {            stringres =NULL; Student Stu=NewStudent {stuid=3, Stuname ="Small white"            }; using(MemoryStream ms=NewMemoryStream ()) {Xmlobjectserializer sz=NULL; if(Format! =NULL&& format. ToLower () = ="XML") {sz=NewDataContractSerializer (Stu.                GetType ()); }                Else{sz=NewDataContractJsonSerializer (Stu.                GetType ()); } sz.                WriteObject (MS, Stu); Res=Encoding.UTF8.GetString (Ms.            ToArray ()); }            returnRes; }    }

Next, configure it in the configuration file.

  <System.ServiceModel>    <Behaviors>      <endpointbehaviors>        <Behaviorname= "HB">          <webhttpautomaticformatselectionenabled= "true"/>        </Behavior>      </endpointbehaviors>    </Behaviors>    <Services>      <Servicename= "Getxmlsample2.myservice">        <EndpointAddress= "http://localhost:2008"binding= "WebHttpBinding"Contract= "Getxmlsample2.idata"behaviorconfiguration= "HB"/>      </Service>    </Services>  </System.ServiceModel>

Two behaviors can be configured under the Behaviors node--service behavior and endpoint behavior. Here we simply configure the behavior of the endpoint, which requires a webhttp element that maps to the WebHttpBehavior class. Remember to assign a name to the behavior node and then, under the/services/service/endpoint node, to refer to the preceding behavior through the Behaviorconfiguration property.

To implement HTTP interaction, you should use WebHttpBinding.

When configuring the webhttp behavior, the value of automaticformatselectionenabled should be set to true so that the content returned to the caller will automatically recognize the format, in fact the primary purpose is to allow the returned string to be stripped of the outermost double quotation marks.

Go back to the code, instantiate ServiceHost, and then open the service.

        Static void Main (string[] args)        {            using (ServiceHost host=new ServiceHost (  typeof(MyService)))            {                host. Open ();                Console.WriteLine (" service is turned on. ");                Console.read ();            }        }

Run the application and enter Http://localhost:2008/getdata?f=xml in the browse to get the result as follows.

Then enter Http://localhost:2008/getdata?f=json to see.

Well, just demonstrate the two methods, you are willing to explore, there are many ways.

Sample source Code

". Net deep Breathing" chat WCF service returns XML or JSON-formatted data

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.