首页 > 代码库 > WCF RestFul例子
WCF RestFul例子
这里没有理论上的东西,仅仅是做下记录。我这个例子偷懒下了,直接在VS2008里面建了个WCF服务应用程序
一、接口,用WebGet的时候需要添加命名空间:System.ServiceModel;System.ServiceModel.Web;
[ServiceContract] public interface IEmployeeService { [WebGet(UriTemplate = "employees", ResponseFormat = WebMessageFormat.Json)] [OperationContract] List<Employee> GetAll(); [WebGet(UriTemplate = "employees/{id}", ResponseFormat = WebMessageFormat.Json)] [OperationContract] Employee GetById(string id); [WebInvoke(Method = "POST", UriTemplate = "add", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)] [OperationContract] void Add(Employee employee); [WebInvoke(Method = "PUT", UriTemplate = "edit", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)] [OperationContract] void Edit(Employee employee); [WebInvoke(Method = "DELETE", UriTemplate = "delete/{id}")] [OperationContract] void Delete(string id); }
二、实体类
[DataContract] public class Employee { [DataMember] public int Id { get; set; } [DataMember] public string Name { get; set; } [DataMember] public string Description { get; set; } }
三、接口实现类
[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)] public class EmployeeService : IEmployeeService { public List<Employee> Employees { get; set; } public EmployeeService() { Employees = new List<Employee> { new Employee{ Id=1, Name="jack",Description="this is jack"}, new Employee{ Id=2, Name="tom",Description="this is tom"}, new Employee{ Id=3, Name="paul",Description="this is paul"} }; } #region IEmployeeService Members public List<Employee> GetAll() { return Employees; } public Employee GetById(string id) { return Employees.FirstOrDefault(e => e.Id == int.Parse(id)); } public void Add(Employee employee) { Employees.Add(employee); } public void Edit(Employee employee) { var entity = Employees.FirstOrDefault(e => e.Id == employee.Id); entity.Name = employee.Name; entity.Description = employee.Description; } public void Delete(string id) { Employees.RemoveAll(e => e.Id == int.Parse(id)); } #endregion }
四、配置文件,
binding="webHttpBinding" 绑定方式一定要用webHttpBinding
<system.serviceModel> <services> <service behaviorConfiguration="WCFRestfulSample.EmployeeServiceBehavior" name="WCFRestfulSample.EmployeeService"> <endpoint address="" binding="webHttpBinding" contract="WCFRestfulSample.IEmployeeService" behaviorConfiguration="WCFRestfulSample.RestfulBehavior"> <identity> <dns value=http://www.mamicode.com/"localhost" /> </identity> </endpoint> <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" /> </service> </services> <behaviors> <endpointBehaviors> <behavior name="WCFRestfulSample.RestfulBehavior"> <webHttp/> </behavior> </endpointBehaviors> <serviceBehaviors> <behavior name="WCFRestfulSample.EmployeeServiceBehavior"> <!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment --> <serviceMetadata httpGetEnabled="true"/> <!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information --> <serviceDebug includeExceptionDetailInFaults="true"/> </behavior> </serviceBehaviors> </behaviors> <!--<bindings> <webHttpBinding> <binding name="defaultRest" > <readerQuotas maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxDepth="64" maxNameTableCharCount="2147483647" /> <security mode="None" /> </binding> </webHttpBinding> </bindings>--> </system.serviceModel>
五、调用过程
const string sUserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.2; .NET CLR 1.1.4322; .NET CLR 2.0.50727)"; const string sContentType = "application/json"; static void Main(string[] args) { Add(); Console.ReadKey(); } static void Select() { HttpWebRequest request = WebRequest.Create("http://localhost:32582/EmployeeService.svc/employees") as HttpWebRequest; request.Method = "GET"; request.ContentType = "text/html;charset=UTF-8"; string result = string.Empty; using (HttpWebResponse response = request.GetResponse() as HttpWebResponse) { using (var reader = new StreamReader(response.GetResponseStream(), Encoding.Default)) { result = reader.ReadToEnd(); } } Console.WriteLine(result); } static void Add() { string url = "http://localhost:32582/EmployeeService.svc/add"; HttpWebRequest httpRequest = WebRequest.Create(url) as HttpWebRequest; httpRequest.UserAgent = sUserAgent; httpRequest.ContentType = sContentType; httpRequest.Method = "POST";
//一定要先序列化然后在写入流 byte[] data =http://www.mamicode.com/ GetPostData(); httpRequest.ContentLength = data.Length; using (Stream requestStream = httpRequest.GetRequestStream()) requestStream.Write(data, 0, data.Length); using (var responseStream = httpRequest.GetResponse().GetResponseStream()) { using (StreamReader responseReader = new StreamReader(responseStream, Encoding.UTF8)) { var result = responseReader.ReadToEnd(); Console.WriteLine("post return result:{0}", result); } } } static byte[] GetPostData() { var employee = new Employee() { Id = 98, Name = "123sdf3", Description = "this is my test..." }; var json = ToJson(employee); Console.WriteLine(json); return Encoding.UTF8.GetBytes(json); } static string ToJson(object item) { DataContractJsonSerializer serializer = new DataContractJsonSerializer(item.GetType()); using (MemoryStream ms = new MemoryStream()) { serializer.WriteObject(ms, item); StringBuilder sb = new StringBuilder(); sb.Append(Encoding.UTF8.GetString(ms.ToArray())); return sb.ToString(); } } [DataContract] public class Employee { [DataMember] public int Id { get; set; } [DataMember] public string Name { get; set; } [DataMember] public string Description { get; set; } }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。