来源:https://github.com/ServiceStack/ServiceStack/wiki/Create-your-first-webservice
1、新建一个空asp.net 项目,用NuGet安装serviceStack包,配置Web.Config
<system.web> <httpHandlers> <add path="*" type="ServiceStack.WebHost.Endpoints.ServiceStackHttpHandlerFactory, ServiceStack" verb="*"/> </httpHandlers> </system.web> <!-- Required for IIS 7.0 (and above?) --> <system.webServer> <validation validateIntegratedModeConfiguration="false" /> <handlers> <add path="*" name="ServiceStack.Factory" type="ServiceStack.WebHost.Endpoints.ServiceStackHttpHandlerFactory, ServiceStack" verb="*" preCondition="integratedMode" resourceType="Unspecified" allowPathInfo="true" /> </handlers> </system.webServer>
2、实现服务
Each service in ServiceStack consists of three parts(每个服务由三部分构成):
- Request DTO
- Service implementation
- Response DTO
//Request DTO输入
using ServiceStack.ServiceHost; [Route("/hello")] [Route("/hello/{Name}")] public class Hello { public string Name { get; set; } }
//Response DTO输出
public class HelloResponse { public string Result { get; set; } }
//实现一个服务
using ServiceStack.ServiceInterface; public class HelloService : Service { public object Any(Hello request) { return new HelloResponse { Result = "Hello, " + request.Name }; } }
3、创建服务主机
public class HelloAppHost : AppHostBase
{
//告诉seviceStack你的服务程序名及如何找到你的服务程序
public HelloAppHost()
: base("Hello Web Services", typeof(HelloService).Assembly) { }
public override void Configure(Funq.Container container)
{
//注册你的服务所使用的任何依赖
//container.Register<ICacheClient>(new MemoryCacheClient());
}
}
//同理,你可以为此而创建多个服务程序主机,以发布多服务程序
4、初始化并启动服务主机,开始发布服务
//Gloabal.cs文件
//注册服务
public class Global : System.Web.HttpApplication { //Initialize your application singleton protected void Application_Start(object sender, EventArgs e) { new HelloAppHost().Init();
//初始化其它服务主机...以实现同一asp.net程序中发布多个服务(note:个人见解) } }