Use ServiceStack to build Web Services and servicestack to build web Services

Source: Internet
Author: User

Use ServiceStack to build Web Services and servicestack to build web Services

When talking about building a WebService, you must first think of using WCF, because it is simple and quick. First of all, I do not know much about WCF, but want to quickly create a WebService. So I saw this article on MSDN: Building Cross-Platform Web Services with ServiceStack, this section briefly introduces how to use ServiceStack to quickly create a WebService.

Before starting, of course, you must first describe what ServiceStack is. There seems to be very few ServiceStack in China, most of which are WCF or ASP. NET WebAPI, the only access to ServiceStack may be when Redis is called in C #, there is a ServiceStack. redis, I also wrote an article earlier.. NET. This ServiceStack. Redis is actually a component of ServiceStack, which is used to interact with ServiceStack.

1. About WebService

Before talking about ServiceStack, let's take a look at the basic framework of a WebService:

Public interface IService {string DoSomething (int input );}

This RPC method makes the service unable to cope with changes. For example, in the above Code, if the interface of a later version needs to accept two parameters to execute the DoSomething method, or return other information besides a string. If it is modified on the original interface, the client of the old version cannot be used. Of course, we can create a parallel DoSomething_v2 to accept two parameters. However, with the migration of time, our interfaces will be filled with more and more such definitions, both new users and old users will be confused.

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

public class DoSomethingRequest{    public int Input { get; set; }}public class DoSomethingResponse{    public string Result { get; set; }}public interface IService{    DoSomethingResponse DoSomething(DoSomethingRequest request);}

Each service receives a DTO request parameter and returns a DTO response. Adding fields to requests and corresponding DTO objects does not destroy the old client.

In WCF, both RPC and DTO-style WebServices are supported, but only DTO-style is supported in ServiceStack. To reduce the complexity and focus on interface design, ServiceStack only embraces the DTO-style remote WebService interface. This is the key to understanding ServiceStack and the design principle of the ServiceStack framework.

After learning about the design concept of ServiceStack, let's take a look at what ServiceStack is.

What is ServiceStack?

ServiceStack is an open-source, very popular WebService framework. Reference 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 service. NET Web Service platform, which simplifies the development of high-performance REST (supporting JSON, XML, JSV, HTML, MsgPack, ProtoBuf, CSV, and other message formats) and wcf soap-style WebService ".

On its homepage, there is also an introduction titled What is the ServiceStack. We recommend that you directly view the following images:

3. Use ServiceStack

To create a service, you must first define an interface. Here we take a ticket sales system as an example to illustrate how to use ServiceStack to create a service:

Create a Service Interface Layer

Create a new TicketSystem. ServiceContract class library. We define the DTO object. You must have a Ticket object class:

public class Ticket{    public int TicketId { get; set; }    public int TableNumber { get; set; }    public int ServerId { get; set; }    public List<Order> Orders { get; set; }    public DateTime Timestamp { get; set; }}

In WCF, you must add DataContract and DataMember to object classes and fields to indicate the fields required for serialization. If these labels are not added, they will be ignored during serialization.

In ServiceStack, these tags are not required. ServiceStack serializes all Plain Old CLR Objects (POCOs) and these Objects are visible to the client.

Then begin to define the interface for external Service provision in the Service:

public interface ITicketService{    List<Ticket> Any(GetAllTicketsInQueueRequest request);    void Any(QueueTicketRequest request);    Ticket Any(PullTicketRequest request);}

In ITickertService, we define three operations. The first time we see such an operation, it may be a bit strange, because the method names are the same. This is different from ServiceStack and WCF. In WCF, the above interfaces may be as follows:

[ServiceContract]public interface ITicketService{    [OperationContract]    List<Ticket> GetAllTicketsInQueue(GetAllTicketsInQueueRequest request);    [OperationContract]    void QueueTicket(QueueTicketRequest request);    [OperationContract]    Ticket PullTicket(PullTicketRequest request);}

In WCF, ServiceContract must be used to indicate the interface, and OperationContract must be used to mark the methods. The method name is the service name.

The service methods in ServiceStack are named Any, Get, and Post. This is also the request type supported by ServiceStack. Any indicates that the service can be called through HTTP Get or HTTP Post. This reinforces and simplifies the implementation of RESTFull-style WebService. You only need to add love [Route (…)] to these methods. Attribute. In ServiceStack, the difference between methods is that service parameters and Request Object Request DTO are differentiated, rather than method names in WCF. This means that a request DTO object cannot be reused in multiple services of ServiceStack.

Create a server

With the service interface layer, you need to write the server to implement these logics, that is, the previously defined ITicketService interface. First, create an empty ASP. NET application named ServiceStackServer, and then create a new TicketService class, which implements the ITicketService interface and inherits from the Service class. The Service class is in ServiceStack. You can use NuGet to install and reference the relevant class library of ServiceStack:

Public class TicketService: Service, ITicketService {private static readonly TicketSystem. ticketProcessor. ticketProcessor _ ticketProcessor = new TicketSystem. ticketProcessor. ticketProcessor (); public List <Ticket> Any (GetAllTicketsInQueueRequest request) {return _ ticketProcessor. getTicketsInQueue (). select (TicketTranslator. translateTicket ). toList ();} public void Any (QueueTicketRequest request ){ _ TicketProcessor. queueTicket (TicketTranslator. translateTicket (request. ticket);} public Ticket Any (PullTicketRequest request) {TicketSystem. ticketProcessor. ticket nextTicket = _ ticketProcessor. pullTicket (); if (nextTicket! = Null) {return TicketTranslator. TranslateTicket (nextTicket);} return null ;}}

Here we define a private TicketProcessor variable. All methods in the interface are implemented through this class. In the call of the interface object to this method, we convert the object. This object is defined in other programs to ensure that the server code is concise.

With the server, you need to Host the server to provide external services. ServiceStack provides multiple forms through IIS, Self-Host, and so on. Because of the ASP. NET program we created earlier, you only need to add a Global. asax file and initialize it in the startup event Application_Start.

protected void Application_Start(object sender, EventArgs e){    //Initialize your web service on startup.    new TicketServiceHost().Init();}

 

public class TicketServiceHost : AppHostBase{    //Register your web service with ServiceStack.    public TicketServiceHost()         : base("Ticket Service", typeof(TicketService).Assembly)     { }    public override void Configure(Funq.Container container)    {        //Register any dependencies your services use here.    }}

You only need to implement the ApphostBase base class, provide the Service display name, and the Assembly of the Service that implements the Service interface.

Of course, you can also Host our WebService through the console application. In this case, TicketServiceHost needs to implement cancelfhostbase as follows:

public class TicketServiceHost : AppSelfHostBase{    /// <summary>    /// Default constructor.    /// Base constructor requires a name and assembly to locate web service classes.     /// </summary>    public TicketServiceHost()        : 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 void Configure(Container container)    {        //Config examples        //this.AddPlugin(new PostmanFeature());        //this.AddPlugin(new CorsFeature());    }}

Then, in the Main function, start:

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, listeningOn);    Console.ReadKey();}

Now, run the created ASP. NET or TicketServiceHost managed by the Console, and access http: // localhost: 1337/in the browser to see the service we have defined:

Static void Main (string [] args) {Console. title = "ServiceStack Console Client"; using (var client = new Soap11ServiceClient ("http: // localhost: 1337") {List <Ticket> queuedTickets = client. send <List <Ticket> (new GetAllTicketsInQueueRequest (); if (queuedTickets! = Null) {foreach (Ticket ticket in queuedTickets) {PrintTicket (ticket) ;}} Console. ReadKey ();}

Here, the Soap11ServiceClient object can be changed to other data serialization formats supported by ServiceStack.

Conclusion 4

This article introduces the popular open-source WebService framework ServiceStack and uses a simple example to show how to use ServiceStack to create a WebService.

It can easily and quickly build an efficient RESTFull-style WebService application. The design concept of the framework is also worth learning. Similar to the "Convention is greater than configuration" method, the various tags required to create WebService in WCF are reduced, force the user to use DTO to create a service interface. ServiceStack also provides the Visual Studio plug-in named ServiceStackVS to help you easily create a ServiceStack template.

WCF can implement all ServiceStack functions. However, ServiceStack provides another option for you to quickly create an efficient WebService, which can run on different platforms. ServiceStack is also an active WebService framework in the open-source community. By studying its code, you can also learn from its ideas to improve your coding and architecture. For example, you can modify the Client to support asynchronous method calls. You can add the desired function by yourself.

I hope this article will help you understand ServiceStack.


How to build a WEB server?

It depends on the system you are using. If you are using Microsoft windows, we recommend that you use iis to plug in the system disk, in the control panel -- add and delete programs -- add and delete components, you can install iis. After setting the root directory, put the webpage file in the root directory.
If you want to publish a domain name, you need a fixed peripheral ip address. If you do not have a fixed peripheral ip address, you can use some software for dynamic domain name resolution.

Web service calling in visual studio

You are still making a web reference because you can reference login in the first solution.
In the second solution, you can. Otherwise, how do you use the first solution.

Next, you can check whether login WebService still exists. Run the first solution test.
If the service is not provided, it cannot be referenced.

Additional questions:
The development server is a lightweight server in the lower right corner for local debugging.
The Web Service developed by your predecessors may be published to IIS (A Real Server), so you cannot see the icon in the lower right corner.

Start WebService without two. in a vs file, right-click your WebService project file, and right-click a Debug file in the menu. you can start WS first. then start your client in the same way. One vs is enough.

Related Article

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.