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;
}
}
}
}

关于WEB消息主体风格的介绍

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服务应用程序的更多相关文章

  1. SharePoint Search之(一):创建Search服务应用程序

    计划写一个关于怎样使用SharePoint Search的系列,包括下面几个方面: (一)创建Search Service Application (二)持续爬网(continues crawl) ( ...

  2. .NET创建一个即是可执行程序又是Windows服务的程序

    不得不说,.NET中安装服务很麻烦,即要创建Service,又要创建ServiceInstall,最后还要弄一堆命令来安装和卸载. 今天给大家提供一种方式,直接使用我们的程序来安装/卸载服务,并且可以 ...

  3. C#/.NET基于Topshelf创建Windows服务的守护程序作为服务启动的客户端桌面程序不显示UI界面的问题分析和解决方案

    本文首发于:码友网--一个专注.NET/.NET Core开发的编程爱好者社区. 文章目录 C#/.NET基于Topshelf创建Windows服务的系列文章目录: C#/.NET基于Topshelf ...

  4. vscode源码分析【四】程序启动的逻辑,最初创建的服务

    第一篇: vscode源码分析[一]从源码运行vscode 第二篇:vscode源码分析[二]程序的启动逻辑,第一个窗口是如何创建的 第三篇:vscode源码分析[三]程序的启动逻辑,性能问题的追踪 ...

  5. vs 2010创建Windows服务定时timer程序

    vs 2010创建Windows服务定时timer程序: 版权声明:本文为搜集借鉴各类文章的原创文章,转载请注明出处:  http://www.cnblogs.com/2186009311CFF/p/ ...

  6. C# 创建Windows Service(Windows服务)程序

    本文介绍了如何用C#创建.安装.启动.监控.卸载简单的Windows Service 的内容步骤和注意事项. 一.创建一个Windows Service 1)创建Windows Service项目 2 ...

  7. ASP.NET MVC 5 03 - 安装MVC5并创建第一个应用程序

    不知不觉 又逢年底, 穷的钞票 所剩无几. 朋友圈里 各种装逼, 抹抹眼泪 MVC 继续走起.. 本系列纯属学习笔记,如果哪里有错误或遗漏的地方,希望大家高调指出,当然,我肯定不会低调改正的.(开个小 ...

  8. 用C#创建Windows服务(Windows Services)

    用C#创建Windows服务(Windows Services) 学习:  第一步:创建服务框架 创建一个新的 Windows 服务项目,可以从Visual C# 工程中选取 Windows 服务(W ...

  9. .Net创建windows服务入门

    本文主要记录学习.net 如何创建windows服务. 1.创建一个Windows服务程序 2.新建安装程序 3.修改service文件 代码如下 protected override void On ...

随机推荐

  1. 关于编程语言(转/收藏)-原文作者:韩天峰(Rango)

    原文在这里:http://rango.swoole.com/archives/405 容易让人记住的文章,要么引起共鸣,要么催人奋进.一句话,你已走过,而我也在路上. 最近群里很多朋友询问我是如何学习 ...

  2. vc++ 内存连续读写操作

    //初始化内存 int *data=(int*)malloc(sizeof(int)*4); ZeroMemory(data, sizeof(int)*4); int *m=(int*)malloc( ...

  3. STM32F0xx_TIM基本延时配置详细过程

    前言 关于定时器大家都应该不会陌生,因为处理器都有这个功能.今天总结的F0系列芯片的定时器根据芯片型号不同,数量也不同.定时器分类:基本定时器.通用定时器和高级定时器.计数位数也有不同,有16位的,有 ...

  4. 关于linux上pdf阅读器

    今天也是倒腾linux 上pdf阅读器好久. 1.okular是挺好的,但是却太大了,好多功能,我没有细看.我简单的打开了几个pdf文件,发现加载速度还是太慢了.所以基于种种,我给卸载掉了. 安装直接 ...

  5. python 关于 ImportError: No module named 的问题

    转载自:http://my.oschina.net/leejun2005/blog/109679 今天在 centos 下安装 python setup.py install 时报错:ImportEr ...

  6. flask 开发记录

    from flask import request 判断method方式 request.method  'POST', ‘GET’ 获取form内容 request.form['form_name' ...

  7. hdu 2094 产生冠军

    题目连接 http://acm.hdu.edu.cn/showproblem.php?pid=2094 产生冠军 Description 有一群人,打乒乓球比赛,两两捉对撕杀,每两个人之间最多打一场比 ...

  8. Java动态替换InetAddress中DNS的做法简单分析2

    import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.i ...

  9. linux php安装zookeeper扩展

    linux php安装zookeeper扩展 tags:php zookeeper linux ext 前言: zookeeper提供很犀利的命名服务,并且集群操作具有原子性,所以在我的多个项目中被采 ...

  10. mvvm 模式

    MVC = Massive View Controller ? 有笑话称MVC为重量级的试图控制器.仔细一想,确实存在这个问题.以UITableViewController和UITableView举个 ...