[WCF] Restful 自定義宿主
阿新 • • 發佈:2017-06-03
targe datetime any ase return using lan esp ges
IPersonRetriever:
/* * 由SharpDevelop創建。 * 用戶: Administrator * 日期: 2017/6/2 * 時間: 22:13 * * 要改變這種模板請點擊 工具|選項|代碼編寫|編輯標準頭文件 */ using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.ServiceModel; using System.ServiceModel.Web; using System.Text; namespace WcfRESTful { /// <summary> /// Description of IPersonRetriever. /// </summary> [ServiceContract] public interface IPersonRetriever { [OperationContract] [WebInvokeAttribute(UriTemplate = "Persons",Method="POST", ResponseFormat = WebMessageFormat.Json)] Person GetPerson(); } [DataContract] public class Person { [DataMember] public string Name { get; set; } [DataMember] public int Age { get; set; } [DataMember] public string Birthday { get; set; } } }
PersonRetriever:
/* * 由SharpDevelop創建。 * 用戶: Administrator * 日期: 2017/6/2 * 時間: 22:15 * * 要改變這種模板請點擊 工具|選項|代碼編寫|編輯標準頭文件 */ using System; using System.ServiceModel.Web; namespace WcfRESTful { /// <summary> /// Description of PersonRetriever. /// </summary> public class PersonRetriever: IPersonRetriever { public Person GetPerson() { WebOperationContext.Current.OutgoingResponse.ContentType = "text/plain"; return new Person { Name = "Test", Age = 22, Birthday = DateTime.Now.ToString("yyyy-mm-dd HH:MM:ss:ffff") }; } } }
Program :
/* * 由SharpDevelop創建。 * 用戶: Administrator * 日期: 2017/6/2 * 時間: 22:19 * * 要改變這種模板請點擊 工具|選項|代碼編寫|編輯標準頭文件 */ using System; using System.ServiceModel; using System.ServiceModel.Description; namespace WcfRESTful { class Program { public static void Main(string[] args) { Console.WriteLine("Hello World!"); // TODO: Implement Functionality Here Uri baseAddress = new Uri("http://127.0.0.1:9998/PersonRetriever"); using (ServiceHost host = new ServiceHost(typeof(PersonRetriever), baseAddress)) { WebHttpBinding binding = new WebHttpBinding(); ServiceEndpoint endpoint = host.AddServiceEndpoint(typeof(IPersonRetriever), binding, baseAddress); WebHttpBehavior httpBehavior = new WebHttpBehavior(); endpoint.Behaviors.Add(httpBehavior); host.Opened += delegate { Console.WriteLine("Hosted successfully."); }; host.Open(); Console.ReadLine(); } Console.Write("Press any key to continue . . . "); Console.ReadKey(true); } } }
截圖 :
源碼: http://files.cnblogs.com/files/Areas/WcfRESTful.zip
[WCF] Restful 自定義宿主