Building cross-platform Web services using ServiceStack (GO)

Source: Internet
Author: User
Tags http post ticket hosting webhost

Source: http://www.cnblogs.com/shanyou/p/3348347.html

This article is primarily from the MSDN Magazine Building cross-platform Web Services with ServiceStack, Windows communication Foundation (WCF) is a very good service framework, when we discuss cross-platform services, although WCF support for WebService, in the face of some advanced applications are not very good, Microsoft has re-developed the ASP. NET Webapi Framework, the discussion of these two frameworks can read my other article " Selection of the WCF and ASP. NET Web API on the app. The ASP is an important option for discussing cross-platform Web services, and in this article I will show how to do this with ServiceStack (open source. NET and Mono REST service framework) without leaving Visual Studio or M Icrosoft.net/mono, in addition to ServiceStack also has a Nancy's framework, specifically can see. NET mini-Web framework Nancy.

A typical WEB service structure is as follows:

    • The service layer is where you define your Web service interfaces. This is also a layer of interaction between the client and your Web service.
    • The business layer is usually the business logic
    • The data layer is designed to encapsulate data access and manipulation to provide an abstract data model at the business level.
    • Web services typically have remote procedure call (RPC) and restful (HTTP) classes, and now the dominant Web service is restful (HTTP), can you see the article, "Rest has been successful in the enterprise?" , put a picture in the article:

2 years ago rest has become the mainstream of Web API deployment, and has maintained this momentum, and is now basically a rest service, and SOAP exists in the enterprise intranet.

Remote Procedure Call (RPC), each request is designed to resemble a function call:

public interface IService

{

string dosomething (int input);

}

The RPC method is very unfriendly to the modification of the service. For example, if the previous code snippet requires two input parameters from the client to perform a later version of the Web service's DoSomething method-or needs to return a field other than the string value-a significant change to the old client is unavoidable. Of course, you can always create a parallel dosomething_v2 method, with two input parameters, but over time will mess up your Web service interface and consumers, the service becomes uglier, the Web service implemented with WCF is the case, the following we introduce Servicestack.

Servicestack is an open-source framework for. NET and Mono, which is a powerful alternative to Web services and Web applications for WCF,MVC and Web APIs, and it is becoming increasingly popular. Web services generated with ServiceStack can run in a Windows environment,. NET code, or mono support in a Linux environment. The operating systems supported by Mono include:

    • Linux
    • Mac OS X, IOS
    • Sun Solaris
    • Bsd
    • Microsoft Windows
    • Nintendo Wii
    • Sony PlayStation 3

Servicestack is the complex of a series of things:

    • Web application framework with high-performance razor engine
    • Support for message-based Web service frameworks in a variety of formats, such as Html,xml,json,soap
    • Container with built-in IOC
    • Several built-in library files, such as: Text Serializer,redis client,orm and caching providers
    • Self-hosting options are included in addition to the ASP. Hosting and Mono Hosting

ServiceStack enforces remote Web services best practices, convention-based DTO standards for their WEB service interfaces, ServiceStack also provides pre-set response state objects that can be used to compose dtos, encourage more direct and simple error handling scenarios, and obviously different routes from WCF.

This article assumes that you have some familiarity with the WCF and. NET Framework. To better demonstrate how WCF concepts can be transformed into ServiceStack concepts, the service layer is implemented first in WCF. I'll show you how to migrate a WCF Web service to the equivalent of using ServiceStack to convert to a cross-platform Web service.

WCF uses data contracts to establish the means of communication between the client and the server. Servicestack and WCF are the same. WCF requires data objects and data members to be labeled; otherwise, WCF simply ignores them. This is a different place for ServiceStack and WCF. ServiceStack supports all Poco objects as a contract:

Contract for WCF:

[DataContract]
public class Ticket
{
[DataMember]
public int Ticketid {get; set;}
[DataMember]
public int Tablenumber {get; set;}
[DataMember]
public int ServerID {get; set;}
[DataMember]
Public list<order> Orders {get; set;}
[DataMember]
Public DateTime Timestamp {get; set;}
}
[ServiceContract]
public interface Iticketservice
{
<summary>
Retrieve a complete list of all tickets in the current queue
</summary>
<returns></returns>
[OperationContract]
List<ticket> Getallticketsinqueue ();

<summary>
New tickets added
</summary>
<param name= "Ticket" ></param>
[OperationContract]
void Queueticket (Ticket Ticket);

<summary>
Pull a ticket out of the queue
</summary>
<returns></returns>
[OperationContract]
Ticket Pullticket ();
}
}

Convert it to Servicestack's contract:

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

}

public class Getallticketsinqueuerequest
{
}

public class Queueticketrequest
{
Public Ticket Ticket {get; set;}
}

public class Pullticketrequest
{
}

public interface Iscticketservice
{
List<ticket> any (getallticketsinqueuerequest request);

void any (queueticketrequest request);

Ticket any (pullticketrequest request);
}

SERVICESTACK specifies that each unique request is a unique request identified by the object, which means that you cannot reuse a DTO to implement a request with ServiceStack across multiple services. ServiceStack supports different operations, such as Get and Post. Your choice here only affects the HTTP request. Specifies that any WEB service request refers to an operation that can be invoked via HTTP GET and HTTP POST. This enforcement simplifies the rest-style WEB service implementation. To turn your ServiceStack Web service into a RESTful Web service, simply add the URL [Route (...)] Declare properties to your Web service request.

Request DTO
public class Hello
{
public string Name {get; set;}
}

Response DTO
public class Helloresponse
{
public string Result {get; set;}
Public ResponseStatus ResponseStatus {get; set;}//where Exceptions get auto-serialized
}

Can is called via any endpoint or format, see:http://servicestack.net/servicestack.hello/
public class Helloservice:service
{
public object any (Hello request)
{
return new Helloresponse {Result = "Hello," + Request. Name};
}
}

   //rest Resource dto 
    [Route ("/todos")] 
     [Route ("/todos/{ids}")] 
    public class todos:ireturn<list<todo>>  
    { 
        public long[] Ids {get; set;} &NBSP
        Public Todos (params long[] IDs)  
         { 
            this. Ids = ids; 
       } 
   }

[Route ("/todos", "POST")]
[Route ("/todos/{id}", "PUT")]
public class Todo:ireturn<todo>
{
Public long Id {get; set;}
public string Content {get; set;}
public int Order {get; set;}
public bool-Done {get; set;}
}

public class Todosservice:service
{
Public todorepository Repository {get; set;} Injected by IOC

public Object Get (Todos request)
{
Return request. Ids.isempty ()
? Repository.getall ()
: Repository.getbyids (Request. IDS);
}

public Object Post (Todo todo)
{
Return Repository.store (TODO);
}

public Object Put (Todo todo)
{
Return Repository.store (TODO);
}

public void Delete (Todos request)
{
Repository.deletebyids (Request. IDS);
}
}

With ASP. Hosting hosting ServiceStack, create an empty ASP. Add the ServiceStack reference to ServiceStack.Host.AspNet as shown in the NuGet Package Manager console

Web. config will add the following configuration

<configuration>
<system.web>
<compilation debug= "True" targetframework= "4.0"/>
<add path= "*" type= "ServiceStack.WebHost.Endpoints.ServiceStackHttpHandlerFactory, ServiceStack" verb= "*"/>
</system.web>
<system.webServer>
<modules runallmanagedmodulesforallrequests= "true"/>
<validation validateintegratedmodeconfiguration= "false"/>
<add path= "*" Name= "servicestack.factory" type= "ServiceStack.WebHost.Endpoints.ServiceStackHttpHandlerFactory, ServiceStack "verb=" * "precondition=" Integratedmode "resourcetype=" Unspecified "allowpathinfo=" true "/>
</system.webServer>
</configuration>

You need to inherit from ServiceStack.WebHost.End to implement the endpoint.

public class Apphost:apphostbase
{
Public AppHost ()//tell ServiceStack the name and where to find your Web services
: Base ("Startertemplate ASP. NET Host", typeof (HelloService). Assembly) {}

        public override void Configure (Funq.container Container)  
        { 
            //set JSON Web services to return idiomatic JSON CamelCase properties 
    & nbsp;       ServiceStack.Text.JsConfig.EmitCamelCaseNames = true; 
         
            //configure User Defined REST paths 
             routes 
             . Add               . Add

Uncomment to change the default ServiceStack configuration
Setconfig (New Endpointhostconfig {
//});

Enable Authentication
Configureauth (container);

Register all your dependencies
Container. Register (New Todorepository ());
}

/* Uncomment to enable ServiceStack authentication and Customusersession
private void Configureauth (Funq.container Container)
{
var appSettings = new AppSettings ();

Default route:/auth/{provider}
Plugins.add (new authfeature () = new Customusersession (),
New iauthprovider[] {
New Credentialsauthprovider (appSettings),
New Facebookauthprovider (appSettings),
New Twitterauthprovider (appSettings),
New Basicauthprovider (appSettings),
}));

Default Route:/register
Plugins.add (New Registrationfeature ());

Requires ConnectionString configured in Web. config
var connectionString = configurationmanager.connectionstrings["appdb"]. ConnectionString;
Container. Register<idbconnectionfactory> (c =
New Ormliteconnectionfactory (connectionString, Sqlserverdialect.provider));

Container. Register<iuserauthrepository> (c =
New Ormliteauthrepository (C.resolve<idbconnectionfactory> ()));

var Authrepo = (ormliteauthrepository) container. Resolve<iuserauthrepository> ();
Authrepo.createmissingtables ();
}
*/

public static void Start ()
{
New AppHost (). Init ();
}
}

When the ServiceStack Web application starts, your service contract is listed as a metadata operation:

Related articles:

SignalR, Filters and ServiceStack

Interview with Servicestack project leader Demis bellot--part 1th

Interview with Servicestack project leader Demis bellot--part 2nd

Building cross-platform Web services using ServiceStack (GO)

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.