您现在的位置是:首页 >技术交流 >RESTful API简介、实战及其Demo(C#)分享网站首页技术交流
RESTful API简介、实战及其Demo(C#)分享
Demo地址
https://gitee.com/chenheze90/L11_RESTfulAPI
或者
https://gitee.com/chenheze90/L11_RESTfulAPI/repository/archive/master.zip
定义
RESTFUL(REST,Rpresentational State Transfer)是一种特定架构风格的接口规范,采用HTTP做传输协议。它不限于某一种开发语言,C#、java等都可以实现。
特点、优点
1、定义清晰明了。每一个URI代表一个资源;
2、操作简单明了。就4个操作GET、POST、PUT、DELETE;
3、分工明确。前后端开发解耦。
4、服务器压力减小。前后端部署不同的服务器。
5、安全性高。
6、相比webservice性能更好。REST+JSON风格的API相比SOAP+XML,调用更加灵活,也更容易扩展;JSON格式传输信息比XML减少约30%的数据量,效率更高。
用途、用法、针对场景
常用的场景:前后端分离,前端可多样化
一套产品可能由多种终端构成,比如PC、web、Android等等。有的系统可能还需要提供对外接口。为了避免后端重复开发,可以采用RESTful API,使所有的接口统一,减少开发量和维护工作。
代码实战-服务端开发
首先新建一个wpf做一个服务端,这里不一定要用wpf,用控制台什么的都可以,看个人喜好。
窗体上要实现两个方法Window_Loaded和Window_Closing,用来实现服务启动和停止。
开发restful api需要引用下面三个dll
新建一个类student
代码如下
using System.Runtime.Serialization;
namespace RESTfulAPI
{
[DataContract]
public class Student
{
[DataMember]
public string Name { get; set; }
[DataMember]
public int Age { get; set; }
}
}
restful api的核心代码,是一个接口interface,有ServiceContract特性的接口。这个是服务的核心逻辑,我们需要增加一个接口,我们所有的接口方法都在上面。代码如下
using System.ServiceModel;
using System.ServiceModel.Web;
namespace RESTfulAPI
{
[ServiceContract]
public interface IStudentQuery
{
[OperationContract]
[WebGet(UriTemplate = "StudentQuery/{name}", ResponseFormat = WebMessageFormat.Json)]
Student GetStudent(string name);
[WebInvoke(UriTemplate = "/StudentQuery/StudentQueryByAge", Method = "POST", ResponseFormat = WebMessageFormat.Json)]
Student GetStudentByage(int age);
}
}
接下来就是接口实现,我们知道单纯的接口不具备任何功能,必须由实现来完成功能,实现如下
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.ServiceModel.Activation;
namespace RESTfulAPI
{
[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single, ConcurrencyMode = ConcurrencyMode.Single, IncludeExceptionDetailInFaults = true)]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class StudentQueryService : IStudentQuery
{
private List<Student> Students = new List<Student>();
public StudentQueryService()
{
Students.Add(new Student() { Name = "张三", Age = 18 });
Students.Add(new Student() { Name = "李四", Age = 17 });
}
public Student GetStudent(string name)
{
return Students.FirstOrDefault(o => o.Name == name);
}
public Student GetStudentByage(int age)
{
return Students.FirstOrDefault(o => o.Age == age);
}
}
}
到这里restful api基本上功能接口就开发完成了。但是接口的运行还有一套机制,就是接口还需要一个承载器。我们称之为服务宿主ServiceHost。
服务宿主承载restful api的方法如下,在主窗体中:
using System;
using System.ServiceModel.Web;
using System.Windows;
namespace RESTfulAPI
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
WebServiceHost _serviceHost;
private void Window_Loaded(object sender, RoutedEventArgs e)
{
StudentQueryService service = new StudentQueryService();
_serviceHost = new WebServiceHost(service, new Uri("http://localhost:8000/Studentsys"));
_serviceHost.Open();
}
private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
_serviceHost.Close();
}
}
}
代码写完之后运行,然后在网页地址中输入:
http://localhost:8000/Studentsys/StudentQuery/张三
查找张三的信息,结果如下
到这里,服务端就开发完了。
代码实战-客户端开发
客户端的开发,也是创建一个wpf程序,增加一个按钮
前台代码
<Window x:Class="Client.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:Client"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<StackPanel>
<Button x:Name="btn1" Content="方法1" Click="btn1_Click" Width="100" Height="20"></Button>
</StackPanel>
</Window>
后台代码
using System;
using System.IO;
using System.Net;
using System.Text;
using System.Windows;
namespace Client
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void btn1_Click(object sender, RoutedEventArgs e)
{
send();
}
public void send()
{
string url = "http://localhost:8000/Studentsys/StudentQuery/StudentQueryByAge";
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
request.Method = "POST";
request.ContentType = "application/json";
string data = "17";
byte[] byteData = UTF8Encoding.UTF8.GetBytes(data.ToString());
request.ContentLength = byteData.Length;
using (Stream postStream = request.GetRequestStream())
{
postStream.Write(byteData, 0, byteData.Length);
}
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
StreamReader reader = new StreamReader(response.GetResponseStream());
txbResult.Text = reader.ReadToEnd();
}
}
}
}
客户端运行起来,点击按钮,可以看到接口调用成功