本文主要介紹ServiceStack的安裝,與第一個項目的創建。
詳細了解ServiceStack,可參考官方網站: https://servicestack.net/,
Github上ServiceStack地址:https://github.com/ServiceStack/ServiceStackVS。
一.安裝
ServiceStack支持vs2012,2013. vs2012的用戶安裝還有2個前提條件:
1. 安裝Microsoft Visual Studio Shell Redistributable。
2. Update to the latest NuGet.
不安裝上面2個包的話,創建項目會報錯,至于NuGet,編譯項目的時候用到。
安裝ServiceStack步驟:
1. 打開vs. Tools->Extensions and Updates.
2. 在Online-> Visual Studio Gallery 里面搜索ServiceStackVS.
3. 搜到后直接安裝,重啟vs,就完成了。
二.創建項目
創建ServiceStackVS項目,打開vs,創建項目,在installed->template->visual C#中,會有8個ServiceStack模版。我們先創建一個空項目。
會有1個solution,4個PRoject. 好了,第一個項目到此完成。
三. Hello world示例
ServiceStack由3部分構成:Request DTO(Data Transefer Object),Service implementation,Response DTO .
1. Request DTO和Response DTO在Webapplication2.ServiceModel項目中的hello.cs中:
[Route("/hello/{Name}")] public class Hello : IReturn<HelloResponse> { public string Name { get; set; } } public class HelloResponse { public string Result { get; set; } }
Route屬性定義了服務訪問服務的方式,部署服務或者運行服務,將瀏覽器地址欄輸入http://<root_path>/hello/world,可以看到結果:
如果要返回json格式,可以在url后面加上 ?format=json。
2 .Service implementation,在WebApplication2.ServiceInterface 項目中MyServices.cs文件中,
public class MyServices : Service { public object Any(Hello request) { return new HelloResponse { Result = "Hello, {0}!".Fmt(request.Name) };
}
}
這定義了返回結果,Any表示可以接受任何(post,get等)http請求。
github上面的英文文檔有很詳細的介紹。https://github.com/ServiceStack/ServiceStack/wiki.
新聞熱點
疑難解答