创建REST服务应用程序
Web服务类别有两种,一种是基于SOAP协议的服务,另一种是基于HTTP协议的REST架构风格的服务。REST服务的数据格式有两种:XML 和 JSON,REST服务已被大量应用于移动互联网中。
本文将简要介绍创建一个REST服务应用程序以及使用它(仅仅是个示例,没有做代码优化)。
一、创建REST服务
1.新建一个空的解决方案,添加“WCF服务应用程序”

2.添加一个服务契约接口:IStudentService.cs,代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ServiceModel;
using System.Runtime.Serialization; namespace RESTService
{
/// <summary>
/// 服务契约:对学生信息进行增删改查
/// </summary>
[ServiceContract]
public interface IStudentService
{
[OperationContract]
string GetStuName(string id); [OperationContract]
Student GetStu(string id); [OperationContract]
bool UpdateStuAge(Student stu); [OperationContract]
bool AddStu(Student stu); [OperationContract]
bool DeleteStu(Student stu);
} /// <summary>
/// 数据契约
/// </summary>
[DataContract]
public class Student
{
[DataMember]
public string ID { get; set; } [DataMember]
public string Name { get; set; } [DataMember]
public int Age { get; set; }
}
}
3.添加REST服务:StudentService.svc,如图:

该服务类实现上述服务契约接口,代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;
using System.Text; namespace RESTService
{
[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class StudentService : IStudentService
{
// 要使用 HTTP GET,请添加 [WebGet] 特性。(默认 ResponseFormat 为 WebMessageFormat.Json)
// 要创建返回 XML 的操作,
// 请添加 [WebGet(ResponseFormat=WebMessageFormat.Xml)],
// 并在操作正文中包括以下行:
// WebOperationContext.Current.OutgoingResponse.ContentType = "text/xml"; private static List<Student> _listStu; public StudentService()
{
_listStu = new List<Student>
{
new Student{ID="",Name="Jim",Age=},
new Student{ID="",Name="Tom",Age=}
};
} [WebGet(UriTemplate = "REST/GetName/{id}", ResponseFormat = WebMessageFormat.Json)]
public string GetStuName(string id)
{
Student stu = this.GetStu(id);
if (stu == null)
{
return "不存在此学生!";
}
else
{
return stu.Name;
}
} [WebGet(UriTemplate = "REST/Get/{id}", ResponseFormat = WebMessageFormat.Json)]
public Student GetStu(string id)
{
Student stu = _listStu.Find(s => s.ID == id);
return stu;
} [WebInvoke(UriTemplate = "REST/Update/", Method = "POST", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare)]
public bool UpdateStuAge(Student stu)
{
Student stu2 = this.GetStu(stu.ID);
if (stu2 == null)
{
return false;
}
else
{
_listStu.Remove(stu2);
_listStu.Add(stu); return true;
}
} [WebInvoke(UriTemplate = "REST/Add/", Method = "PUT", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare)]
public bool AddStu(Student stu)
{
if (_listStu == null)
{
_listStu = new List<Student>();
} _listStu.Add(stu);
return true;
} [WebInvoke(UriTemplate = "REST/Delete/", Method = "DELETE", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare)]
public bool DeleteStu(Student stu)
{
Student stu2 = this.GetStu(stu.ID);
if (stu2 == null)
{
return false;
}
else
{
_listStu.Remove(stu2);
return true;
}
}
}
}
4.WebConfig文件内容:
<?xml version="1.0" encoding="utf-8"?>
<configuration> <appSettings>
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5"/>
</system.web>
<system.serviceModel>
<services>
<service name="RESTService.StudentService">
<endpoint address="" behaviorConfiguration="RESTService.StudentServiceAspNetAjaxBehavior"
binding="webHttpBinding" contract="RESTService.IStudentService" />
</service>
</services>
<behaviors>
<endpointBehaviors>
<behavior name="RESTService.StudentServiceAspNetAjaxBehavior">
<!--<enableWebScript />-->
<webHttp helpEnabled="true"/>
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior name="">
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="true" />
</behavior>
</serviceBehaviors>
</behaviors>
<protocolMapping>
<add binding="basicHttpsBinding" scheme="https" />
</protocolMapping>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true"
multipleSiteBindingsEnabled="true" />
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
<!--
若要在调试过程中浏览 Web 应用程序根目录,请将下面的值设置为 True。
在部署之前将该值设置为 False 可避免泄露 Web 应用程序文件夹信息。
-->
<directoryBrowse enabled="true"/>
</system.webServer> </configuration>
5.在浏览器中查看REST服务信息

在浏览器地址栏的url后面输入help,即可查看该服务提供了哪些操作

二、调用REST服务
1.为了演示方便,本例采用WinForm应用程序调用REST服务(当然你也可以使用Android,IOS,IPad,WP等等其他客户端进行测试),界面效果如图:

2.后台代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Runtime.Serialization.Json;
using RESTService;
using System.IO; namespace RESTClient
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
} /// <summary>
/// Json 反序列化
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="jsonString"></param>
/// <returns></returns>
public static T JsonDeserialize<T>(string jsonString)
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
T obj = (T)serializer.ReadObject(ms);
return obj;
} /// <summary>
/// Json 反序列化
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="ms"></param>
/// <returns></returns>
public static T JsonDeserialize<T>(Stream ms)
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
T obj = (T)serializer.ReadObject(ms);
return obj;
} /// <summary>
/// Json 序列化
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="t"></param>
/// <returns></returns>
public static string JsonSerializer<T>(T t)
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
using (MemoryStream ms = new MemoryStream())
{
serializer.WriteObject(ms, t);
return Encoding.UTF8.GetString(ms.ToArray());
}
} /// <summary>
/// GET 操作
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnGet_Click(object sender, EventArgs e)
{
string uri = string.Format("http://localhost:4563/StudentService.svc/rest/get/{0}", this.txtID.Text.Trim());
HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(uri);
wr.Method = "GET";
HttpWebResponse resp = (HttpWebResponse)wr.GetResponse();
if (resp.ContentLength <= )
{
MessageBox.Show("不存在此学生!");
this.txtID.Text = "";
this.txtName.Text = "";
this.txtAge.Text = "";
}
else
{
Stream ms = resp.GetResponseStream();
Student stu = JsonDeserialize<Student>(ms);
this.txtID.Text = stu.ID;
this.txtName.Text = stu.Name;
this.txtAge.Text = stu.Age.ToString();
}
} /// <summary>
/// POST 操作
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnPost_Click(object sender, EventArgs e)
{
string uri = string.Format("http://localhost:4563/StudentService.svc/rest/update/");
Student stu = new Student();
stu.ID = this.txtID.Text.Trim();
stu.Name = this.txtName.Text.Trim();
stu.Age = Convert.ToInt32(this.txtAge.Text.Trim());
byte[] bs = Encoding.UTF8.GetBytes(JsonSerializer<Student>(stu));
HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(uri);
wr.Method = "POST";
wr.ContentLength = bs.Length;
wr.ContentType = "application/json";
using (Stream reqStream = wr.GetRequestStream())
{
reqStream.Write(bs, , bs.Length);
}
HttpWebResponse resp = (HttpWebResponse)wr.GetResponse();
using (Stream respStream = resp.GetResponseStream())
{
StreamReader sr = new StreamReader(respStream);
string result = sr.ReadToEnd();
if (result == "true")
{
MessageBox.Show("更新成功!");
}
else
{
MessageBox.Show("更新失败!");
}
}
} /// <summary>
/// PUT 操作
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnPut_Click(object sender, EventArgs e)
{
string uri = string.Format("http://localhost:4563/StudentService.svc/rest/add/");
Student stu = new Student();
stu.ID = this.txtID.Text.Trim();
stu.Name = this.txtName.Text.Trim();
stu.Age = Convert.ToInt32(this.txtAge.Text.Trim());
byte[] bs = Encoding.UTF8.GetBytes(JsonSerializer<Student>(stu));
HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(uri);
wr.Method = "PUT";
wr.ContentLength = bs.Length;
wr.ContentType = "application/json";
using (Stream reqStream = wr.GetRequestStream())
{
reqStream.Write(bs, , bs.Length);
}
HttpWebResponse resp = (HttpWebResponse)wr.GetResponse();
using (Stream respStream = resp.GetResponseStream())
{
StreamReader sr = new StreamReader(respStream);
string result = sr.ReadToEnd();
if (result == "true")
{
MessageBox.Show("添加成功!");
}
else
{
MessageBox.Show("添加失败!");
}
}
} /// <summary>
/// DELETE 操作
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnDelete_Click(object sender, EventArgs e)
{
string uri = string.Format("http://localhost:4563/StudentService.svc/rest/delete/");
Student stu = new Student();
stu.ID = this.txtID.Text.Trim();
byte[] bs = Encoding.UTF8.GetBytes(JsonSerializer<Student>(stu));
HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(uri);
wr.Method = "DELETE";
wr.ContentLength = bs.Length;
wr.ContentType = "application/json";
using (Stream reqStream = wr.GetRequestStream())
{
reqStream.Write(bs, , bs.Length);
}
HttpWebResponse resp = (HttpWebResponse)wr.GetResponse();
using (Stream respStream = resp.GetResponseStream())
{
StreamReader sr = new StreamReader(respStream);
string result = sr.ReadToEnd();
if (result == "true")
{
MessageBox.Show("删除成功!");
}
else
{
MessageBox.Show("删除失败!");
}
}
}
}
}
创建REST服务应用程序的更多相关文章
- SharePoint Search之(一):创建Search服务应用程序
计划写一个关于怎样使用SharePoint Search的系列,包括下面几个方面: (一)创建Search Service Application (二)持续爬网(continues crawl) ( ...
- .NET创建一个即是可执行程序又是Windows服务的程序
不得不说,.NET中安装服务很麻烦,即要创建Service,又要创建ServiceInstall,最后还要弄一堆命令来安装和卸载. 今天给大家提供一种方式,直接使用我们的程序来安装/卸载服务,并且可以 ...
- C#/.NET基于Topshelf创建Windows服务的守护程序作为服务启动的客户端桌面程序不显示UI界面的问题分析和解决方案
本文首发于:码友网--一个专注.NET/.NET Core开发的编程爱好者社区. 文章目录 C#/.NET基于Topshelf创建Windows服务的系列文章目录: C#/.NET基于Topshelf ...
- vscode源码分析【四】程序启动的逻辑,最初创建的服务
第一篇: vscode源码分析[一]从源码运行vscode 第二篇:vscode源码分析[二]程序的启动逻辑,第一个窗口是如何创建的 第三篇:vscode源码分析[三]程序的启动逻辑,性能问题的追踪 ...
- vs 2010创建Windows服务定时timer程序
vs 2010创建Windows服务定时timer程序: 版权声明:本文为搜集借鉴各类文章的原创文章,转载请注明出处: http://www.cnblogs.com/2186009311CFF/p/ ...
- C# 创建Windows Service(Windows服务)程序
本文介绍了如何用C#创建.安装.启动.监控.卸载简单的Windows Service 的内容步骤和注意事项. 一.创建一个Windows Service 1)创建Windows Service项目 2 ...
- ASP.NET MVC 5 03 - 安装MVC5并创建第一个应用程序
不知不觉 又逢年底, 穷的钞票 所剩无几. 朋友圈里 各种装逼, 抹抹眼泪 MVC 继续走起.. 本系列纯属学习笔记,如果哪里有错误或遗漏的地方,希望大家高调指出,当然,我肯定不会低调改正的.(开个小 ...
- 用C#创建Windows服务(Windows Services)
用C#创建Windows服务(Windows Services) 学习: 第一步:创建服务框架 创建一个新的 Windows 服务项目,可以从Visual C# 工程中选取 Windows 服务(W ...
- .Net创建windows服务入门
本文主要记录学习.net 如何创建windows服务. 1.创建一个Windows服务程序 2.新建安装程序 3.修改service文件 代码如下 protected override void On ...
随机推荐
- php变量那些事:php引擎对变量声明、存储简要分析(ZVAL)
php中变量有三个基本的特性: 1.变量符号.也就是变量的名称.形象比喻,kv中的key.这个有php引擎的符号表(hash表)管理. 2.变量类型.一个php变量可以是boolean.integer ...
- public void onItemClick(AdapterView arg0, View view, int position,long arg3)详解【整理自网络】
参考自: http://blog.csdn.net/zwq1457/article/details/8282717 http://blog.iamzsx.me/show.html?id=147001 ...
- Bootstrap 2.3.2学习
1.下载架包,下载编译好的文件,文件目录结构如下所示: bootstrap/ ├── css/ │ ├── bootstrap.css │ ├── bootstrap.min.css ├── js/ ...
- opensuse 安装 Anaconda3 之后出现Could not start d-bus. Can you call qdbus?
最近在安装了opensue Leap42.1之后,想要学习一下python,就安装了Anaconda3,并且将Anaconda3的安装路径添加到了PATH里,但是在重新启动系统后,出现了"C ...
- [terry笔记]Oracle会话追踪(一):SQL_TRACE&EVENT 10046
SQL_TRACE/10046 事件是 Oracle 提供的用于进行 SQL 跟踪的手段,在日常的数据库问题诊断和解决中是非常常用的方法.但其生成的trace文件需要tkprof工具生成一个可供人 ...
- Telerik XML 数据源绑定的问题
Telerik GridView 默认的 XElement 数据源的直接绑定,会导致内置的sort, filter ,group等功能无法使用. 原因在于Telerik GridView的那些功能是根 ...
- PF_RING 实验
前提:pf_ring.ko 运行在模式2 收包实验: 使用两台机器同时对装PF_RING的机器进行发包,此机器的网卡流量达到14M的效果.如下所示: 上图为PF_RING自 ...
- 禁止生成文件Thumbs.db
Thumbs.db是一个用于Microsoft Windows XP.Windows7 或 mac os x缓存Windows Explorer的缩略图的文件.Thumbs.db保存在每一个包含图片或 ...
- sed实例一则
1.背景: test.txt文件里有这些语句 li^E1026^D20150802B07QH800^B698.^C20150801B08CDP00^B514.^C20150803D00A8L00^B2 ...
- Python: 迭代器与生成器小结
迭代器与生成器的区别: 1. 迭代器由Class对象创建. 生成器由包含yield表达的Function对象或者Generator Expression创建. 2. 迭代器的原理: (1)由Itera ...