Linux學習日記-WCF RestFul的部署(三)
阿新 • • 發佈:2018-12-27
一、關於WCF 的部署
預設的wshttp風格的wcf是很容易部署上去的,但是這裡給個建議儘量不要使用WCF的配置檔案去部署儘管
我們都已經很熟悉了,在使用配置檔案你會發現各種蛋疼的問題。
二、WCF Restful的部署
以下是簡單的目錄:
最主要的是主機的程式碼:
注: 一定要用程式碼,而不用配置檔案 否則幫助頁、預設返回格式什麼的以配置就報異常
介面IService 類 using System; using System.Runtime.Serialization; using System.ServiceModel; usingSystem.ServiceModel.Web; namespace Services { [ServiceContract] public interface IService { [OperationContract,WebGet(UriTemplate="test/{name}")] string GetData (string name); } } 服務Service 類 using System; namespace Services { public class Service:IService {public string GetData(string name) { return name; } } } 主機啟動服務的方法: using System; using System.Runtime.Serialization; using System.ServiceModel; using System.ServiceModel.Web; using System.ServiceModel.Description; using Services; namespace Hosting {class MainClass { public static void Main (string[] args) { using (WebServiceHost host = new WebServiceHost (typeof(Services.Service))) { //host.AddServiceEndpoint(typeof(ICalculator), new WebHttpBinding(), "http://127.0.0.1:9999/"); ServiceEndpoint endpoint = host.AddServiceEndpoint(typeof(Services.IService), new WebHttpBinding(), "http://127.0.0.1:9999/"); if (host.Description.Behaviors.Find<WebHttpBehavior> () == null) { WebHttpBehavior httpBehavior = new WebHttpBehavior (); httpBehavior.HelpEnabled = true; //開啟幫助頁 httpBehavior.DefaultOutgoingResponseFormat = WebMessageFormat.Json;//指定返回格式為“Json” httpBehavior.DefaultBodyStyle = WebMessageBodyStyle.Bare; //正文訊息樣式 httpBehavior.AutomaticFormatSelectionEnabled = false; //是否自動返回格式 endpoint.Behaviors.Add (httpBehavior);//新增終結點 } host.Opened += delegate { Console.WriteLine ("服務已啟動!"); }; host.Open(); Console.ReadKey(); } } } }
using System;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
namespace Services
{
[ServiceContract]
publicinterfaceIService
{
[OperationContract,WebGet(UriTemplate="test/{name}")]
stringGetData(stringname);
}
}