WCF implements restful Web Service

Source: Internet
Author: User

Together to learn some of the previous concepts, finally began to the point of the ha. RESTful Web service calls are intuitive and return content is easy to parse. Here we'll describe a simple scenario--web service provides a way to search for personal information, pass in a person's name, and return complete personal information.
Let's step through WCF to implement a restful web Service. After this is described separately with the normal console program host locally, and with IIS published to the network.

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;}
}
}

It is important to note that the WebGetAttribute is above the method Getperson ():
1.1 WebGetAttribute defines how this method is accessed as a restful get (for restful you can refer to the article in this blog about rest introduction).
1.2 uritemplet describes the URL matching format, and when the format matches, a string of {name} position is passed in as the method parameter.
1.3 Responseformat Specifies the data format to be returned, with options of JSON and 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 = $, Birthday = DateTime.Now};
}
}
}

In this implementation, we simply return a person instance with the passed-in Name argument as name. Add here: If Contecttype is "Text", if the result string is returned contains special characters (such as escape, double quotation marks, XML file fragments, etc.), some cases will be parsed in the IE is not normal, resulting in missing fields, there is no relevant data to explain the IE parsing rules. For convenience and prudence, use "Text/plain" directly.

3. Host Service in console

On the 1th, 2-step basis, we started this service in console host.

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 ();
}
}
}
}

After that we can access the service via Url:http://127.0.0.1:9998/personretriever/persons/tom, where "Tom" is the name of the person who needs to be queried. Enter the URL in IE and the result after carriage return is as follows:


4. In IIS, host Web Service

4.1 Create a new WCF service (or a different Web service depending on the. Net Framework version) project, copy the contract and implementation of the 1th, 2 steps 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 results 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 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 BEFO Re Deployment--
<servicemetadata httpgetenabled= "true"/>
<!--to receive exception details on 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, and we can get the result above by Url:http://16x.19x.18x.6x/wcftest/service.svc/persons/tom {"Age": "Birthday ":" \/date (1329226087212-0500) \ "," Name ":" Tom "}.

One thing to add here is that in 4.1 steps, we create a new Web service project, just to write down some of the configuration of the config (which will default to System.web,complier, etc.), in fact we can create the App_Code folder entirely. You can successfully deploy and use the contact and contract implementations by copying them into the folder and then manually creating the Service.svc,web.config on the outer layer and writing the appropriate matching content.

5. Summary
RESTful Web Service uses a simpler, more generic protocol (HTTP, less SOAP encapsulation and parsing), a more straightforward result, and a good choice in situations where resources don't require interactive logic and complex structures.

Http://www.cnblogs.com/KeithWang/archive/2012/02/14/2351826.html

WCF implements restful Web Service

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.