Implementing RESTFul Web Service using WCF

Source: Internet
Author: User

I learned some of the previous concepts and finally started my topic. Restful web service calls are intuitive, and the returned content is easy to parse. Here, we will describe a simple scenario -- Web Service provides a method to search for personal information, input personal names, and return complete personal information.
Next we will use WCF to implement a restful web service step by step. After that, we will describe using the common console program host on the local machine and publishing it to the network using IIS.

1. Contract

namespace WcfRESTful
{
[ServiceContract]
public interface IPersonRetriever
{
[OperationContract]
[WebGet(UriTemplate = "Persons/{name}", ResponseFormat = WebMessageFormat.Json)]
Person GetPerson(string name);
}

[DataContract]
public class Person
{
[DataMember]
public string Name { get; set; }
[DataMember]
public int Age { get; set; }
[DataMember]
public DateTime Birthday { get; set; }
}
}

Here, you need to note the webgetattribute on the getperson () method:
1.1 webgetattribute defines the access method of this method as restful get (for details about restful, refer to the rest article in this blog ).
1.2 uritemplet describes the URL matching format. When the format matches, the string at the {name} position is passed as a method parameter.
1.3 responseformat specifies the format of returned data, which can be JSON or XML.

 

2. Contract implementation

namespace WcfRESTful
{
public class PersonRetriever : IPersonRetriever
{
public Person GetPerson(string name)
{
WebOperationContext.Current.OutgoingResponse.ContentType = "text/plain";
return new Person { Name = name, Age = 22, Birthday = DateTime.Now };
}
}
}

In this implementation, we simply return a person instance with the input name parameter name. Note: If the contecttype is "text", if the returned result string contains special characters (such as escape, double quotation marks, XML file fragments, etc.), the parsing in IE may fail, the field is missing. No information is found to describe the Internet Explorer parsing rules. "Text/plain" is directly used for convenience and caution ".

 

3. Host Service in the Console

On the basis of step 2, we start to host the service in the console.

namespace WcfRESTful
{
class Program
{
static void Main(string[] args)
{
Uri baseAddress = new Uri("http://127.0.0.1:9998/PersonRetriever");
using (ServiceHost host = new ServiceHost(typeof(PersonRetriever), baseAddress))
{
WebHttpBinding binding = new WebHttpBinding();
ServiceEndpoint endpoint = host.AddServiceEndpoint(typeof(IPersonRetriever), binding, baseAddress);
WebHttpBehavior httpBehavior = new WebHttpBehavior();
endpoint.Behaviors.Add(httpBehavior);
host.Opened += delegate
{
Console.WriteLine("Hosted successfully.");
};
host.Open();
Console.ReadLine();
}
}
}
}

Let's use URL: http: // 127.0.0.1: 9998/personretriever/persons/Tom to access the service. "Tom" is the name of the person to be queried. Enter the URL in IE. the result after the carriage return is as follows:

4. Host Web Service in IIS

4.1 create a new WCF Service (or Web Service depends on the. Net Framework Version) project and Copy the Contract and implementation in step 1 and 2 to the App_Code folder.

4.2 modify Service. svc-note that Factory = "System. ServiceModel. Activation. WebServiceHostFactory" must be added before you can view the result directly in IE, but Matedata will be blocked and cannot be displayed.

<%@ ServiceHost Language="C#" Debug="true" Service="WcfRESTful.PersonRetriever" CodeBehind="~/App_Code/PersonRetriever.cs" Factory="System.ServiceModel.Activation.WebServiceHostFactory"%>

4.3 add an Endpoint to Web. config

    <system.serviceModel>
<services>
<service name="WcfRESTful.PersonRetriever" behaviorConfiguration="ServiceBehavior">
<endpoint binding="webHttpBinding" contract="WcfRESTful.IPersonRetriever"/>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="ServiceBehavior">
<!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
<serviceMetadata httpGetEnabled="true"/>
<!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information -->
<serviceDebug includeExceptionDetailInFaults="true"/>
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>

4.4 Add the project directory to the IIS virtual path named WCFTest.

All the steps above 4.1-4.4 have been completed. We use URL: http: // 16X. 19X. 18X. 6X/wcftest/Service. svc/Persons/Tom can get the above results {"Age": 22, "Birthday": "\/Date (1329226087212-0500) \/", "Name ": "Tom "}.

Here, we need to add that in Step 4.1, we create a Web Service project to write less Web. config configuration (system is used by default. web, complier, and other configuration information), in fact, we can create a new App_Code folder, the Contact and Contract implementation into this folder, and then manually create a Service in the outer layer. svc, Web. config and write the corresponding configuration content, which can be successfully deployed and used.

 

5. Summary
RESTful Web Service uses a simpler and more general protocol (HTTP, with less SOAP encapsulation and resolution). More direct results make people shine, it is a good choice when resources do not require interaction logic and complex structures.

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.