最近用 WPF 启动 WCF REST 服务, 发现 App.config 配置好烦, 简单一个 exe 可以到处搬动, 还非得带一个累赘配置, 不小心丢了程序就跑不起来.
最后决定, 砍去 WCF 配置项, 用 webServiceHost 简单启动服务, 监听端口与路径写在注册表中. WPF 程序给一个配置项配置端口与路径项.
- [ServiceContract]
- public interface IHomeService
- {
- [OperationContract]
- [WebGet(UriTemplate = "Get/{id}", RequestFormat = WebMessageFormat.JSON,ResponseFormat = WebMessageFormat.JSON)]
- string Get(string id);
- [OperationContract]
- [WebInvoke(Method = "POST", UriTemplate = "Add", RequestFormat = WebMessageFormat.JSON,ResponseFormat = WebMessageFormat.JSON)]
- string Add(string stu);
- }
- public class HomeService : IHomeService
- {
- public string Get(string id)
- {
- return "Get" + id;
- }
- public string Add(string id)
- {
- return "Add" + id;
- }
- }
- public class WebApi
- {
- private static WebServiceHost _host;
- /// <summary>
- /// 开启服务
- /// </summary>
- /// <param name="url"> 监听路径 (http://127.0.0.1:3721/abc)</param>
- public static void Open(string url)
- {
- if (_host==null)
- {
- Uri baseAddress = new Uri(url);
- _host = new WebServiceHost(typeof(HomeService), baseAddress);
- _host.Open();
- }
- }
- }
更多详细内容 可以看 Artech 的详细分解
https://www.cnblogs.com/artech/archive/2012/02/15/wcf-rest.html
[WCF REST] WebServiceHost 不依赖配置文件启动简单服务
来源: http://www.bubuko.com/infodetail-3061581.html