Building Web Services using Servicestack

Source: Internet
Author: User
Tags http post

When it comes to building webservice services, you must be the first to think about using WCF because it's quick and easy. The first thing to note is that I don't know much about WCF, but want to quickly build a webservice and see this article on MSDN Building Cross-platform Web Services with ServiceStack, So here's a quick overview of how to use Servicestack to quickly build a webservice service.

Of course, before you begin, let's start by explaining what Servicestack is. In the domestic use of servicestack seems to be very few, most of them are WCF or ASP. WebAPI, the only contact servicestack may be in C # when calling Redis, there is a servicestack.redis, before also wrote an article. NET in the use of Redis. This servicestack.redis is actually a component of servicestack that is designed to interact with Redis.

One about WebService

Before talking about Servicestack, look at the basic framework that makes up a webservice:

The service layer is where the WebService interface is defined, and this layer is the only layer that the client needs to interact with with WebService.

The business layer typically contains a large number of business logic. He is also the place to implement interface-layer-defined interfaces, as well as to maintain the lightweight of the service layer and focus on the contract and communication of the server-side client.

The data layer is typically the encapsulation of data access methods and provides an abstract data model to the business layer.

Now let's take a look at the service layer. Some webservice use the remote procedure call method to implement (RPC), for example, the following function call is defined:

 Public Interface iservice{    string dosomething (int  input);}

This RPC approach makes the service unable to respond well to changes. For example, in the above code, if the subsequent version of the interface needs to accept two parameters to execute the DoSomething method, or to return a string, but also need to return additional information. If modified on the original interface, it will make the old version of the client unusable. Of course, we can create a parallel dosomething_v2 to accept two parameters. But as time goes on, our interface will be filled with more and more of these definitions, both new and old users will be confused.

In this case, you can use a data transfer object (DTO) to define the relevant parameters in the preceding interface. The above RPC mode is converted to the corresponding DTO model as follows:

 Public class dosomethingrequest{    publicintgetset;}}  Public class dosomethingresponse{    publicstringgetset;}  Public Interface iservice{    dosomethingresponse dosomething (dosomethingrequest request);}

Each service accepts a DTO request parameter and returns a DTO response. Adding a field to the request and the corresponding Dto object does not break the old client.

RPC and DTO-style webservice are supported in WCF, but only DTO style is supported in Servicestack. Servicestack is designed to reduce cumbersome and attention to the interface design thereby embracing only the DTO-style remote WebService interface. This is the key to understanding Servicestack, but also the design principles of the Servicestack framework.

After understanding the design concept of servicestack, let's look at what Servicestack is.

What are two servicestack?

Servicestack is an open source, very popular WebService framework, citing the introduction of its official website:

Service Stack is a high-performance. NET Web Services platform that simplifies the development of High-performance REST ( JSON, XML, JSV, HTML, Msgpack, Protobuf, CSV) and WCF SOAP Web Services. "

"Servicestack is a high-performance. NET Web Service platform that simplifies the development of high-performance rest (message formats such as JSON,XML,JSV,HTML,MSGPACK,PROTOBUF,CSV) and WCF SOAP-style WebService ".

An introduction to the Servicestack is also available on its homepage. It is recommended that you look directly, and here are a few pictures from the inside:

You can see that servicestack in addition to being a streamlined webservice framework on its bottom, there are components associated with it, such as the fastest JSON serialization tool known as. NET. NET in the popular Redis access module, Lightweight fast ORM Framework Ormlite and many other features.

You can see that these components provide basic functionality necessary for a WebService framework.

The internal implementation of Servicestack was built on the native ASP. NET IHttpHandler, and he was able to allow it on top of the. NET Framework and Mono.

Here's how to build a WebService using Servicestack:

Three use Servicestack

To create a service, you first define the interface. Here is an example of how to use Servicestack to create a service using a ticketing system:

Creating the Service Interface layer

First create a new Ticketsystem.servicecontract class library, and we define the Dto object. You must have a ticket entity class:

 Public classticket{ Public intTicketid {Get;Set; }  Public intTablenumber {Get;Set; }  Public intServerID {Get;Set; }  PublicList<order> Orders {Get;Set; }  PublicDateTime Timestamp {Get;Set; }}

In WCF you need to add DataContract and DataMember to the entity classes and fields to represent the fields required for serialization, and if they are not added, they are ignored at serialization time.

In Servicestack, these tags are not required, and servicestack serializes all plain old CLR Objects (Pocos), and these objects are visible to the client.

It then begins to define the interfaces that are needed in the service for external servicing:

 Public Interface iticketservice{    List<Ticket> any (getallticketsinqueuerequest request);     void Any (queueticketrequest request);    Ticket any (pullticketrequest request);}

In Itickertservice, we defined three operations, and it might be strange to see such operations for the first time because the method names are the same. This is a different place for servicestack and WCF. The above interface may be the same in WCF:

[ServiceContract]  Public Interface iticketservice{    [OperationContract]    List<Ticket> getallticketsinqueue ( Getallticketsinqueuerequest request);    [OperationContract]     void Queueticket (queueticketrequest request);    [OperationContract]    Ticket Pullticket (pullticketrequest request);}

Interfaces in WCF need to use ServiceContract to indicate that their methods need to be tagged with operationcontract. The name of the method is the name of the service.

The service method in Servicestack is named Any,get and post, which is also the type of request supported by Servicestack, and any means that the service can be called via HTTP GET and HTTP POST two. This reinforces and simplifies the implementation of the Restfull style of webservice. Just add love to these methods [Route (...)] property. In Servicestack, the difference between a method and a method is differentiated by the parameters of the service and by the request object requests Dto, rather than by the method name in WCF. This means that a request for a Dto object cannot be reused in multiple service servicestack.

Create a service-side

With the service interface layer, you need to write the service side to implement these logic, which is the Iticketservice interface defined earlier. Start by creating an empty ASP. NET application named Servicestackserver, and then create a new Ticketservice class, which is the class that implements the Iticketservice interface and inherits from the service class. The service class is in Servicestack and can be used to install and reference the Servicestack related class library through NuGet:

The following Ticketservice classes are implemented:

 Public classTicketservice:service, iticketservice{Private Static ReadOnlyTicketSystem.TicketProcessor.TicketProcessor _ticketprocessor=NewTicketSystem.TicketProcessor.TicketProcessor ();  PublicList<ticket>Any (Getallticketsinqueuerequest request) {return_ticketprocessor.getticketsinqueue (). Select (Tickettranslator.translateticket).    ToList (); }     Public voidAny (Queueticketrequest request) {_ticketprocessor.queueticket (tickettranslator.translateticket (Request.    Ticket)); }     PublicTicket any (pullticketrequest request) {TicketSystem.TicketProcessor.Ticket Nextticket=_ticketprocessor.pullticket (); if(Nextticket! =NULL)        {            returnTickettranslator.translateticket (Nextticket); }        return NULL; }}

In this we define a private ticketprocessor variable, and all the methods in the interface are implemented by the class, and in the interface object to the method's invocation, we convert the entity. This object is defined in other assemblies to ensure that the server code is concise.

With the service side, you need to host the server to provide services to the outside, Servicestack provides through iis,self-host and many other forms. Because of the ASP. NET program that we created earlier, we just need to add another Global.asax file and initialize it in the event Application_Start that started.

protected voidApplication_Start (Objectsender, EventArgs e) {    //Initialize your Web service on startup.    NewTicketservicehost (). Init ();}  Public classticketservicehost:apphostbase{//Register your Web service with ServiceStack.     Publicticketservicehost ():Base("Ticket Service",typeof(Ticketservice). Assembly) {} Public Override voidConfigure (Funq.container Container) {//Register Any dependencies your services with here.    }}

Just implement the Apphostbase base class, provide the service display name, and the assembly where the service interface's services are implemented.

Of course, you can also use the console application to host our WebService, Ticketservicehost need to implement Appselfhostbase, the following:

 Public classticketservicehost:appselfhostbase{/// <summary>    ///Default Constructor. ///Base Constructor requires a name and assembly to locate Web service classes. /// </summary>     Publicticketservicehost ():Base("WebApplication1",typeof(Ticketservice). Assembly) {}/// <summary>    ///Application Specific Configuration///This method should initialize any IoC resources utilized by your Web service classes. /// </summary>    /// <param name= "container" ></param>     Public Override voidConfigure (Container Container) {//Config Examples//This .        Addplugin (New Postmanfeature ()); //This . Addplugin (New Corsfeature ());    }}

The

is then started in the main function:

 static  void  Main (string  [] args) { var  Listeningon = args. Length = = 0 ?  " http://*:1337/ : Args[0      var  appHost = new   Ticketservicehost (). Init ().    Start (Listeningon); Console.WriteLine (  apphost Created at { 0}, listening on {1}   , DateTime.Now, list    Eningon); Console.readkey ();}  

Now, we run the previously created ASP. NET or run console-hosted Ticketservicehost, and access http://localhost:1337/in the browser to see our defined services:

Service Client

After the server is created and managed, the service consumer can directly write the HttpWebRequest object to directly access the services via get or post.

In addition to this, Servicestack has built-in clients with convenient access, which are located in the ServiceStack.ServiceClient.Web namespace. All built-in clients implement ServiceStack.Service.IServiceClient, and these rest-enabled clients implement ServiceStack.Service.IRestClient. These client objects include:

    • Jsonserviceclient
    • Jsvserviceclient
    • Xmlserviceclient
    • Msgpackserviceclient
    • Protobufserviceclient
    • Soap11serviceclient
    • Soap12serviceclient

As you can see from the name, there are several differences between the supported serialization and deserialization formats. Because they implement a series of identical interfaces, their usage is the same and can be replaced.

Here we do not show how to request the webservice that we previously hosted through HttpWebRequest like requesting a normal Web page, now suppose we have a console program that needs to use the WebService program. You only need to create a new Servicestack service and then pass in the address of host. These methods internally will translate the code into traditional requests using HttpWebRequest, which are still synchronous.

For example, if we want to use the SOAP11 used in WCF to request, just the following code:

Static voidMain (string[] args) {Console.title="ServiceStack Console Client"; using(varClient =NewSoap11serviceclient ("http://localhost:1337") ) {List<Ticket> queuedtickets = client. Send<list<ticket>>(            Newgetallticketsinqueuerequest ()); if(Queuedtickets! =NULL)        {            foreach(Ticket Ticketinchqueuedtickets)            {PrintTicket (ticket); }}} Console.readkey ();}

The Soap11serviceclient object here can be replaced with other data serialization formats supported by Servicestack.

Four conclusion

This article introduces the more popular WebService framework Servicestack for open source, and shows a simple example of how to create a webservice using Servicestack.

It makes it easier and quicker to build an efficient WebService application with restfull style. The design of its framework is also well worth learning, by reducing the variety of tags that are needed to create webservice in WCF, and forcing users to use DTOs to establish service interfaces in a way that is similar to "Convention over configuration". Servicestack also provides a VisualStudio plugin called Servicestackvs to help you easily create Servicestack templates.

WCF can implement all of the Servicestack functionality. But Servicestack provides another option for you to quickly create an efficient webservice that he can run on different platforms. Servicestack is also an active WebService framework for the open source community, and by studying its code, it can also learn from its ideas and improve its coding and architecture level. For example, you can modify the client to support asynchronous method calls, and so on, you can add the function you want.

I hope this article will help you understand servicestack.

Building Web Services using Servicestack

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.