Our target:
We will be creating a WCF Service in azure which will have rest based urls. The functionality of this wcf service along with rest based urls are:
Functionality | Rest based URL | HTTP Verb |
View all Movies | movies/now-playing | GET |
Coding the WCF Service:
Creating the basic wcf service
Added a new Azure Cloud Project
And then added a WCF service role.
By running this without any changes we can get a basic WCF service up.
Creating the contracts for the service
Before modifying the service we will add contracts so that the client and service have a common structure to refer. So we add new project with the following interfaces, since we need to access the movie object in both service and in the client we will add the following interface in the go4cinemaApi.Contracts project.
public interface IDataMovie
{
string Movie
{
get;
set;
}
string ShortDescription
{
get;
set;
}
string Image
{
get;
set;
}
}
Create the Data Contract in the wcf Service
Now in the wcf service project we will add a data contract which will implement the above interface, we will decorate it with the proper wcf attributes to expose this.
[DataContract]
public class DataMovie :
IDataMovie
{
[DataMember]
public string Movie
{
get;
set;
}
[DataMember]
public string ShortDescription
{
get;
set;
}
[DataMember]
public string ImagePath
{
get;
set;
}
}
Implementing the wcf service with dummy data.
[ServiceContract]
public interface IMovies
{
[OperationContract]
IEnumerable<DataMovie> NowPlaying()
}
public class Movies : IMovies
{
public IEnumerable<DataMovie> NowPlaying()
{
yield return new DataMovie { Movie = "mv-1", ImagePath = "mv-1-img", ShortDescription = "desc of mv-1" };
yield return new DataMovie { Movie = "mv-2", ImagePath = "mv-2-img", ShortDescription = "desc of mv-2" };
}
}
Making the wcf service restful:
To make the wcf service restful we make the following changes:
- In the Movies.svc file we open in markup mode and then modify the svc file and add a WebServiceHostFactory to its factory attribute such that it looks like :
<%@ ServiceHost
Language="C#"
Service="go4cinemaWcfApi.Movies"
CodeBehind="Movies.svc.cs"
Factory="System.ServiceModel.Activation.WebServiceHostFactory"
%>
2. Then in the Movies service class we add the webget attribute to the operation method nowplaying() such that I looks like :
public class Movies : IMovies
{
[WebGet(ResponseFormat = WebMessageFormat.Xml)]
public IEnumerable<DataMovie> NowPlaying()
{
yield return new DataMovie { Movie = "mv-1", ImagePath = "mv-1-img", ShortDescription = "desc of mv-1" };
yield return new DataMovie { Movie = "mv-2", ImagePath = "mv-2-img", ShortDescription = "desc of mv-2" };
}
}
Now if we run this service and visit the Movies.svc/nowplaying you will get the xml. The source can be got from codeplex here.
No comments:
Post a Comment