[Practice] A simple WCF RESTFul Service

Source: Internet
Author: User

There are a lot of REST instances on the Internet for WCF. Here I learned and practiced it over the past few days. It's a note.

1. Service Contract

[ServiceContract] public interface IRESTService {}

Note the following parameters in the specific operation definition:

1. The difference between WebGet and WebInvoke is that Method is defined differently. WebGet uses "GET" and WebInvoke is more flexible.
2. UriTemplate uses the {value} parameter list.
3. WebMessageFormat includes XML and JSON. There is an article on the Internet to implement RAW, which has not been carefully studied yet.

        A simple example is to customize

        1 [OperationContract]
        2 [WebGet (UriTemplate = "{name }? Token = {token} ", ResponseFormat = WebMessageFormat. Json)]
        3 Person GetPerson (string name, string token );

        And

        1 [OperationContract]
        2 [WebGet (UriTemplate = "Data/{id }? Token = {token} ")]
        3 Stream GetData (string id, string token );

        Note that the variable type in the definition is string. In addition, the token is intended for simple authentication in the future and is not clear yet. It is not in the scope of this discussion.

        2. Host

        It is best to use WebServiceHost directly,

        WebServiceHost restHost = new WebServiceHost (typeof (RESTService), new Uri ("http: // localhost/RestService "));

        ServiceHost is a little complicated, but it is more flexible.

        1 ServiceHost GetRestHost (Uri baseAddress)
        2 {
        3 ServiceHost host = new ServiceHost (typeof (RESTService), baseAddress );
        4 WebHttpBinding binding = new WebHttpBinding ();
        5 ServiceEndpoint endpoint = host. AddServiceEndpoint (typeof (IRESTService), binding, baseAddress );
        6 WebHttpBehavior httpBehavior = new WebHttpBehavior ();
        7 endpoint. Behaviors. Add (httpBehavior );
        8 return host;
        9}

        3. Specific Operation instance

        3.0 define a simple data contract first

        1 [DataContract]
        2 public class Person
        3 {
        4 [DataMember] public string Name {get; set ;}
        5 [DataMember] public DateTime Birthday {get; set ;}
        6}

        I have left a DateTime type of data, which will be used when I prepare for future research on the client. Isn't it true that the json Date Processing in js is different from that in WCF.

        3.1 example of a returned string (JSON)

        1 public Person GetPerson (string name, string token)
        2 {
        3 return new Person {Name = name, Birthday = DateTime. Now };
        4}

        In this way, access the following address:

        Http: // localhost/RestService/Tom? Token = 123

        The following result is displayed:

        1 {
        2 Birthday: "/Date (1241764517437 + 0800 )/"
        3 Name: "Tom"
        4}

        We recommend that you install the jsonview plug-in of Firefox to view the results.

        3.2 Example of returning a binary image)

        1 public Stream GetData (string id, string token)
        2 {
        3 WebOperationContext. Current. OutgoingResponse. ContentType = "image/jpeg ";
        4 MemoryStream MS = new MemoryStream ();
        5 try
        6 {
        7 Bitmap bmp = new Bitmap (@ "E: \ 1.jpg ");
        8 bmp. Save (MS, bmp. RawFormat );
        9 ms. Position = 0;
        10 bmp. Dispose ();
        11 return MS;
        12}
        13 catch (Exception e)
        14 {
        15 Console. WriteLine (e. ToString ());
        16 return null;
        17}
        18}

        Here we will simply read the file and actually plan to use the database.

        1. I would like to say a little more about this. One is the issue of Stream releasing resources. I have not figured out whether the platform will Dispose or Close it after interaction.
        2. The other is that the method that uses byte [] for the return value type is not called. The returned data is base64-encoded and marked with XML.
        3. Pay attention to the value assignment of ContentType. Other non-text types should be similar and have not been verified.
        4. When transferring large files, you can modify the maxcompute messagesize and ReaderQuotas of Binding. maxStringContentLength, SendTimeout, and ReceiveTimeout solve the problem of too much data and timeout. However, I always feel that it is strange to use WCF to transmit data within 10 MB, which is too big.

            Now, visit

            Http: // localhost/RestService/Data/100? Token = 200

            The image is displayed in the browser.

            Success!

             

            Welcome to the discussion and make progress together.

            Please indicate the source for reprinting. Please reply to the post for help :)

            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.