服务端
1.新建空白解决方案,然后再空白解决方案中新建:WCF服务应用程序。建完后如图:
2.删掉自动生成的IService1.cs和Service.svc并添加WCF服务文件StudentService.svc,VS会自动生成IStudentService.cs 在添加一个Student类,如图:
Student.cs:
/// <summary>
/// DataContract数据约定,保证student类在WCF调用中被序列化
/// DataMember 在被序列化的成员变量中必须加 [DataMember]标签
/// </summary>
[DataContract]
public class Student
{
[DataMember]
public string StudentId { get; set; }
[DataMember]
public string StudentName { get; set; }
}
IStudentService.cs:
/// <summary>
/// ServiceContract:服务约定,代表我们所能操作的接口集合,提 供功能点。
/// OperationContract: 每个对外需要发布的方法都需要加上此标签
/// </summary>
[ServiceContract]
public interface IStudentService
{
[OperationContract]
List<Student> RemoveStudent(string id);
}
StudentService.svc:
public class StudentService : IStudentService
{ public List<Student> RemoveStudent(string id)
{
var students = new List<Student>() {
new Student {StudentId="",StudentName="学生1" },
new Student {StudentId="",StudentName="学生2" }
}; var student = students.Find(m => m.StudentId == id); students.Remove(student); return students;
}
}
到现在为止我们WCF服务端程序建好了,我们把StudentService.svc设为起始页,F5运行一下,会弹出来WCF测试客户端,如图
双击左侧的RemoveStudent(),在右侧输入值然后点击调用,如图:
结果如我们预料的那样,StudentId为1的数据被删掉了。
接下来我们把它部署到IIS上, 在默认文档里添加StudentService.svc,然后浏览,如图:
客户端
1.新建空白解决方案,新建ASP.NET WEB应用程序,名称为WCFClient,添加服务引用,服务引用地址为上图地址中的
http://localhost:88/StudentService.svc?wsdl
,如图:
WCFTest.aspx:
<form id="form1" runat="server">
<div>
<table>
<tr>
<td> <asp:TextBox ID="txtStudentId" runat="server"></asp:TextBox></td>
<td><asp:Button ID="btnSubmint" runat="server" Text="删除" OnClick="btnSubmint_OnClick"/></td>
</tr>
</table> </div>
</form>
WCFTest.aspx.cs:
protected void btnSubmint_OnClick(object sender, EventArgs e)
{
var wcfService = new WCFService.StudentServiceClient(); var str = string.Empty; wcfService.RemoveStudent(this.txtStudentId.Text.Trim())
.ToList()
.ForEach(m =>str += m.StudentId + ":" + m.StudentName); Response.Write(str);
}
运行下,看下效果: