C#编程实现HTTP访问(二)
- PUT操作:修改指定的Employee信息
protected async void Button5_Click(object sender, EventArgs e)
{
string url = "http://me.hubwiz.com/RestWcfService/employee";
HttpClient client = new HttpClient();
Employee em = new Employee();
em.Id = "005";
em.Grade = "G9";
em.Department = "生活秘书";
em.Name = "Lily";
StringContent theContent = new StringContent( JsonHelper.JsonSerializer<Employee>(em), System.Text.Encoding.UTF8, "application/json");
using (HttpResponseMessage message = await client.PutAsync(url, theContent))
{
message.EnsureSuccessStatusCode();
this.GetALL();
}
}
如上面代码所示,修改Id为005的Employee信息,然后使用HttpClient以PUT请求的方式将该对象发送至服务端,点击按钮执行后,页面输出结果如下:
- DELETE操作: 删除指定id的Employee对象
protected async void Button4_Click(object sender, EventArgs e)
{
string url = "http://me.hubwiz.com/RestWcfService/employee";
HttpClient client = new HttpClient();
using (HttpResponseMessage message = await client.DeleteAsync(url + TextBox1.Text))
{
message.EnsureSuccessStatusCode();
GetALL();
}
}
删除文本框中所输入Id的Employee对象,如上面代码所示。删除时访问地址为url/id形式,然后使用HttpClient以DELETE请求的方式访问服务,页面输出结果如下,可见删除操作成功了:
至此,CURD操作都已经完成。HTTP方式访问Restful WCF服务时,无需对客户端应用进行配置,这也进一步体现出REST服务的便利性。
查看WCFClient应用中WebForm1.aspx、JsonHelper的代码,学习序列化的应用;运行页面,抓取数据包,分析CRUD动作的执行过程。