最近用WPF启动 WCF REST 服务,发现app.config 配置好烦,简单一个exe 可以到处搬动,还非得带一个累赘配置,不小心丢了程序就跑不起来。
最后决定,砍去WCF配置项,用WebServiceHost 简单启动服务,监听端口与路径写在注册表中。WPF程序给一个配置项配置端口与路径项。
1 [ServiceContract] 2 public interface IHomeService 3 { 4 [OperationContract] 5 [WebGet(UriTemplate = "Get/{id}", RequestFormat = WebMessageFormat.Json,ResponseFormat = WebMessageFormat.Json)] 6 string Get(string id); 7 8 [OperationContract] 9 [WebInvoke(Method = "POST", UriTemplate = "Add", RequestFormat = WebMessageFormat.Json,ResponseFormat = WebMessageFormat.Json)]10 string Add(string stu);11 }12 13 public class HomeService : IHomeService14 {15 public string Get(string id)16 {17 return "Get " + id;18 }19 20 public string Add(string id)21 {22 return "Add " + id;23 }24 }25 26 public class WebApi27 {28 private static WebServiceHost _host;29 30 ///31 /// 开启服务32 /// 33 /// 监听路径(http://127.0.0.1:3721/abc)34 public static void Open(string url)35 {36 if (_host==null)37 {38 Uri baseAddress = new Uri(url);39 _host = new WebServiceHost(typeof(HomeService), baseAddress);40 _host.Open();41 }42 }43 }
更多详细内容 可以看 Artech 的详细分解
https://www.cnblogs.com/artech/archive/2012/02/15/wcf-rest.html