勇哥注:
wcf的REST服务,其实就是WCF Web HTTP服务,跟web api相似。
由于WebServiceHost已经包含了ServiceHost的所有功能,并额外添加了Web HTTP端点的支持。
如果你想同时包含SOAP端点和REST端点,可以在app.config中一并定义了。
客户端:


浏览器访问的效果:


Service.Interface
Contract.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using System.Threading.Tasks;
namespace Contract
{
[DataContract(Namespace = "http://www.artech.com/")]
public class Employee
{
[DataMember]
public string Id { get; set; }
[DataMember]
public string Name { get; set; }
[DataMember]
public string Department { get; set; }
[DataMember]
public string Grade { get; set; }
public override string ToString()
{
return string.Format("ID: {0,-5}姓名: {1, -5}级别: {2, -4} 部门: {3}", Id, Name, Grade, Department);
}
}
[ServiceContract(Namespace = "http://www.artech.com/")]
public interface IEmployees
{
[WebGet(UriTemplate = "all")]
IEnumerable<Employee> GetAll();
[WebGet(UriTemplate = "{id}")]
Employee Get(string id);
[WebInvoke(UriTemplate = "/", Method = "POST")]
void Create(Employee employee);
[WebInvoke(UriTemplate = "/", Method = "PUT")]
void Update(Employee employee);
[WebInvoke(UriTemplate = "{id}", Method = "DELETE")]
void Delete(string id);
}
}Service 是一个控制台程序
Program.cs
using Contract;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.ServiceModel.Web;
using System.Text;
using System.Threading.Tasks;
namespace Service
{
class Program
{
static void Main(string[] args)
{
using (WebServiceHost host = new WebServiceHost(typeof(EmployeesService)))
{
host.Open();
Console.Read();
}
}
}
public class EmployeesService : IEmployees
{
private static IList<Employee> employees = new List<Employee>
{
new Employee{ Id = "001", Name="张三", Department="开发部", Grade = "G7"},
new Employee{ Id = "002", Name="李四", Department="人事部", Grade = "G6"}
};
public Employee Get(string id)
{
Employee employee = employees.FirstOrDefault(e => e.Id == id);
if (null == employee)
{
WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.NotFound;
}
return employee;
}
public void Create(Employee employee)
{
employees.Add(employee);
}
public void Update(Employee employee)
{
this.Delete(employee.Id);
employees.Add(employee);
}
public void Delete(string id)
{
Employee employee = this.Get(id);
if (null != employee)
{
employees.Remove(employee);
}
}
public IEnumerable<Employee> GetAll()
{
return employees;
}
}
}app.config
<?xml version="1.0" encoding="utf-8" ?> <configuration> <startup> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" /> </startup> <system.serviceModel> <services> <service name="Service.EmployeesService"> <endpoint address="http://127.0.0.1:3721/employees" binding="webHttpBinding" contract="Contract.IEmployees"/> </service> </services> </system.serviceModel> </configuration>
Client 客户端应用
是个winform程序。
using Contract;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.ServiceModel;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Client
{
public partial class Form1 : Form
{
ChannelFactory<IEmployees> channelFactory = null;
IEmployees proxy;
public Form1()
{
InitializeComponent();
channelFactory = new ChannelFactory<IEmployees>("employeeService");
proxy = channelFactory.CreateChannel();
}
Stopwatch sw1 = new Stopwatch();
private void BtnDisAll_Click(object sender, EventArgs e)
{
try
{
RtbMsg.Text = "";
sw1.Restart();
employeeList = proxy.GetAll().ToList();
sw1.Stop();
long tick = sw1.ElapsedTicks;
if (Stopwatch.IsHighResolution)
{
// 计时器刻度是高性能计时器滴答数
RtbMsg.AppendText("使用系统高分辨率性能计数器计时:\n");
double data = tick * (1000L * 1000L * 1000L) / Stopwatch.Frequency;
Debug.WriteLine($"{data}ns,{data / 1000.0}us,{data / 1000.0 / 1000.0}ms ");
}
Array.ForEach<Employee>(employeeList.ToArray(), employee
=> RtbMsg.AppendText($"Id={employee.Id},Name={employee.Name},Grade={employee.Grade},Department={employee.Department}\n"));
updateCombox();
}
catch(Exception ex)
{
Debug.WriteLine(ex.Message);
}
}
private void BtnAddNew_Click(object sender, EventArgs e)
{
RtbMsg.Text = "";
proxy.Create(new Employee
{
Id = TxtId.Text,
Name = TxtName.Text,
Grade =TxtGrade.Text ,
Department =TxtDepartment.Text
});
employeeList = proxy.GetAll().ToList();
Array.ForEach<Employee>(employeeList.ToArray(), employee
=> RtbMsg.AppendText($"Id={employee.Id},Name={employee.Name},Grade={employee.Grade},Department={employee.Department}\n"));
updateCombox();
}
private void BtnModify_Click(object sender, EventArgs e)
{
proxy.Update(new Employee
{
Id = TxtId.Text,
Name = TxtName.Text,
Grade = TxtGrade.Text,
Department = TxtDepartment.Text
});
RtbMsg.Text = "";
employeeList = proxy.GetAll().ToList();
Array.ForEach<Employee>(employeeList.ToArray(), employee
=> RtbMsg.AppendText($"Id={employee.Id},Name={employee.Name},Grade={employee.Grade},Department={employee.Department}\n"));
updateCombox();
}
private void BtnDel_Click(object sender, EventArgs e)
{
var idx = employeeList.FindIndex(s => s.Name == comboBox1.Text);
if (idx >= 0)
{
proxy.Delete(employeeList[idx].Id);
}
RtbMsg.Text = "";
employeeList = proxy.GetAll().ToList();
Array.ForEach<Employee>(employeeList.ToArray(), employee
=> RtbMsg.AppendText($"Id={employee.Id},Name={employee.Name},Grade={employee.Grade},Department={employee.Department}\n"));
updateCombox();
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
try
{
channelFactory.Close();
}
catch
{
channelFactory.Abort();
}
}
private void updateCombox()
{
employeeList = proxy.GetAll().ToList();
comboBox1.Items.Clear();
employeeList.ForEach((s) =>
{
comboBox1.Items.Add(s.Name);
});
}
private void Form1_Load(object sender, EventArgs e)
{
updateCombox();
}
private List<Employee> employeeList = new List<Employee>();
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
var idx= employeeList.FindIndex(s => s.Name == comboBox1.Text);
if(idx>=0)
{
TxtId.Text = employeeList[idx].Id;
TxtName.Text = employeeList[idx].Name;
TxtGrade.Text = employeeList[idx].Grade;
TxtDepartment.Text = employeeList[idx].Department;
}
}
}
}源码下载:
链接:https://pan.baidu.com/s/1-iag6I69v9DsYm7b2B2nZQ
提取码:ywj3
--来自百度网盘超级会员V6勇哥的分享