09.12 ASP.NET Core RESTful Web服务开发教程

在本文中,我将逐步解释如何在ASP.NET Core中开发基于RESTful的Web服务应用程序。ASP.NET Core是微软最新发布的技术,比之前的WCF和Web API要好得多。

前提:

1、下载最新版本的Microsoft Visual Studio。他们有一个用于实践的免费许可版本。

2、为了测试这个应用程序,下载SOAPUI工具,因为我们将使用SOAPUI工具来测试所有服务。

让我们一步一步的开始我们的项目:

步骤1:首先,创建一个ASP.NET Core Web应用程序项目在Visual Studio中命名为StudentRegistrationDemo3。为此,选择File->New->Project->ASP.NET Core Web应用程序(参见下面的窗口)并单击OK。

ASP.NET Core RESTful Web服务开发教程


一旦您单击OK按钮,你会看到下面的窗口,你需要选择“Web应用程序”,取消“配置HTTPS的复选框(否则,它将创建一个基于ssl的项目,你必须使用HTTPS instad在你的所有url的HTTP测试)并单击OK按钮。

ASP.NET Core RESTful Web服务开发教程


单击OK按钮后,将创建以下项目结构:

ASP.NET Core RESTful Web服务开发教程


步骤2:现在需要在项目中添加两个文件夹:一个用于Models,另一个用于Controllers。Models 文件夹用于资源类,Controllers文件夹用于控制器类;这是这个项目所需要的。右键点击你的项目, Add=>New Folder 并相应地重新命名。

ASP.NET Core RESTful Web服务开发教程


最后,您的项目结构如下:

ASP.NET Core RESTful Web服务开发教程


步骤3:现在,我们将创建以下资源类来处理GET、POST、PUT和DELETE服务。右键单击project explorer窗口中的Models文件夹,选择Add=>Class(参见下面):

ASP.NET Core RESTful Web服务开发教程


现在修改Student Class如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace StudentRegistrationDemo3.Models
{
public class Student
{
String name;
public String Name
{
get { return name; }
set { name = value; }
}
int age;
public int Age
{
get { return age; }
set { age = value; }
}
String registrationNumber;
public String RegistrationNumber
{
get { return registrationNumber; }
set { registrationNumber = value; }
}
}
}

现在按照上面的步骤,分别添加两个类:StudentRegistration和StudentRegistrationReply,并对它们进行如下修改:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace StudentRegistrationDemo3.Models
{
public class StudentRegistration
{
List<student> studentList;
static StudentRegistration stdregd = null;
private StudentRegistration()
{
studentList = new List<student>();
}
public static StudentRegistration getInstance()
{
if (stdregd == null)
{
stdregd = new StudentRegistration();
return stdregd;

}
else
{
return stdregd;
}
}
public void Add(Student student)
{
studentList.Add(student);
}
public String Remove(String registrationNumber)
{
for (int i = 0; i < studentList.Count; i++)
{
Student stdn = studentList.ElementAt(i);
if (stdn.RegistrationNumber.Equals(registrationNumber))
{
studentList.RemoveAt(i);//update the new record
return "Delete successful";
}
}
return "Delete un-successful";
}
public List<student> getAllStudent()
{
return studentList;
}
public String UpdateStudent(Student std)
{
for (int i = 0; i < studentList.Count; i++)
{
Student stdn = studentList.ElementAt(i);
if (stdn.RegistrationNumber.Equals(std.RegistrationNumber))
{
studentList[i] = std;//update the new record
return "Update successful";
}
}
return "Update un-successful";
}
}
}
\tusing System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace StudentRegistrationDemo3.Models
{
public class StudentRegistrationReply
{

String name;
public String Name
{
get { return name; }
set { name = value; }
}
int age;
public int Age
{
get { return age; }
set { age = value; }
}
String registrationNumber;
public String RegistrationNumber
{
get { return registrationNumber; }
set { registrationNumber = value; }
}
String registrationStatus;
public String RegistrationStatus
{
get { return registrationStatus; }
set { registrationStatus = value; }
}
}
}
/<student>/<student>/<student>

步骤4:现在是引入控制器类来处理我们的GET、POST、PUT和DELETE web请求的时候了。在本例中,我们将为GET、POST、PUT和DELETE请求创建单独的Controller,尽管这不是必须的,但为了更清楚起见,我使用了单独的Controller。即使一个Controller也可以满足上述所有服务,但是,按照良好的设计原则,我们应该有一个单独的Controller,以便易于维护和调试应用程序。

让我们先从GET和POST请求开始。单击Controllers文件夹并选择Add=>New Item,然后选择“API Controller类”并创建一个名为StudentRetriveController的控制器类,用于处理GET请求,如下所示。

ASP.NET Core RESTful Web服务开发教程


并修改控制器类如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using StudentRegistrationDemo3.Models;
namespace StudentRegistrationDemo2.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class StudentRetriveController : Controller
{
// GET: api/<controller>
[HttpGet]
public List<student> GetAllStudents()

{
return StudentRegistration.getInstance().getAllStudent();
}
[HttpGet("GetAllStudentRecords")]
public JsonResult GetAllStudentRecords()
{
return Json(StudentRegistration.getInstance().getAllStudent());
}
}
}
/<student>/<controller>

现在,按照上面的步骤,添加一个控制器类StudentRegistrationController来处理POST请求和修改类,如下所示:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using StudentRegistrationDemo3.Models;
namespace StudentRegistrationDemo3.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class StudentRegistrationController : Controller
{
// POST: api/<controller>
[HttpPost]
public StudentRegistrationReply RegisterStudent(Student studentregd)
{
Console.WriteLine("In registerStudent");
StudentRegistrationReply stdregreply = new StudentRegistrationReply();
StudentRegistration.getInstance().Add(studentregd);
stdregreply.Name = studentregd.Name;
stdregreply.Age = studentregd.Age;
stdregreply.RegistrationNumber = studentregd.RegistrationNumber;
stdregreply.RegistrationStatus = "Successful";
return stdregreply;
}
[HttpPost("InsertStudent")]
public IActionResult InsertStudent(Student studentregd)
{
Console.WriteLine("In registerStudent");
StudentRegistrationReply stdregreply = new StudentRegistrationReply();
StudentRegistration.getInstance().Add(studentregd);
stdregreply.Name = studentregd.Name;
stdregreply.Age = studentregd.Age;

stdregreply.RegistrationNumber = studentregd.RegistrationNumber;
stdregreply.RegistrationStatus = "Successful";
return Ok(stdregreply);
}
[Route("student/")]
[HttpPost("AddStudent")]
public JsonResult AddStudent(Student studentregd)
{
Console.WriteLine("In registerStudent");
StudentRegistrationReply stdregreply = new StudentRegistrationReply();
StudentRegistration.getInstance().Add(studentregd);
stdregreply.Name = studentregd.Name;
stdregreply.Age = studentregd.Age;
stdregreply.RegistrationNumber = studentregd.RegistrationNumber;
stdregreply.RegistrationStatus = "Successful";
return Json(stdregreply);
}
}
}
/<controller>

我们完成了第一阶段,现在是测试应用程序的时候了

步骤5:在Visual Studio菜单栏中,可以看到一个绿色箭头按钮。在这里,您可以选择安装在系统中的浏览器并单击它。它将启动web服务器并运行web服务应用程序。

ASP.NET Core RESTful Web服务开发教程


现在等待,直到你的浏览器窗口加载正确如下:

ASP.NET Core RESTful Web服务开发教程


现在服务器正在运行,我们将首先执行GET服务调用。

步骤6。我希望您已经在系统中安装了SOAPUI;如果没有,请从这里下载SOAPUI。现在打开应用程序,从文件菜单中选择“New REST项目”(文件=>New REST项目),复制粘贴下面的URL并单击OK按钮。请更改端口号63662,因为您的情况可能有所不同。

http://localhost:63662/api/studentretrive

(注意,我们使用的URL具有controller名studentretritrive (StudentRetriveController),作为 resource locator)

ASP.NET Core RESTful Web服务开发教程


一旦项目被创建,只需点击绿色箭头按钮,你可以看到一个空记录文件夹如下:

ASP.NET Core RESTful Web服务开发教程


原因很明显,因为我们的Student list 是空的。我们需要插入一些记录。要添加记录,我们将使用POST服务。现在让我们测试一下我们的POST service。

步骤7、按照步骤6,创建一个新的REST项目,并添加下面的URL。

http://localhost:63662/api/studentregistration

但是,这里,我们需要做一些额外的配置。首先,从方法列表中选择POST,并在媒体类型中添加记录,以便将其插入应用程序。现在,单击绿色箭头按钮,您可以看到下面的窗口。

ASP.NET Core RESTful Web服务开发教程


现在,看看StudentRegistrationController类。在这里,我介绍了四种不同类型的邮政服务。引入四种不同类型的POST方法的原因是为了向您提供一个使用泛型类型作为返回类型的示例。在第一个POST service方法RegisterStudent中,返回类型是用户定义类型StudentRegistrationReply。假设在插入过程中我们得到一个异常;我们如何通知调用者异常类型?因为返回类型是StudentRegistrationReply,我们必须返回类型为StudentRegistrationReply的对象。因此,我们需要一个泛型返回类型,这样我们就可以返回任何对象类型。但是,我们有办法处理这种情况。现在看看其他的方法;返回类型是泛型的,我们使用JSON以便我们可以翻转任何类型的对象。

现在,使用URL http://localhost:63662/api/studentregistration/InsertStudent调用使用InsertStudent (InsertStudent不是case san吧)的POST方法。注意,这里的返回类型是IActionResult,这是一个泛型类型。但是返回类型实现逻辑与第一个方法完全相同,它只是用来添加一条记录。还要注意[HttpPost("InsertStudent")],这有助于我们设计资源路径。现在您必须在资源路径的末尾添加InsertStudent方法。通过这种方式,我们可以设计一个不同的资源路径来在控制器中执行不同的方法。

ASP.NET Core RESTful Web服务开发教程


现在我们要测试第三种方法,AddStudent。这三种方法都在执行相同的操作,即向学生列表中添加记录。但是它们有不同的返回类型和不同的资源路径。我的意图非常明确。首先,从方法返回对象的不同方法是什么?其次,我们如何设计不同的资源路径(路由)来调用特定的web方法?

现在使用URL http://localhost:63662/api/studentregistration/student调用AddStudent方法,其中返回类型是JsonResult。如果返回XML消息,我们不能将其作为返回类型使用,在这种情况下,我们必须将IActionResult作为通用返回类型使用。

ASP.NET Core RESTful Web服务开发教程


现在重复GET测试,看看结果:

ASP.NET Core RESTful Web服务开发教程


在上面的截图中,我们插入了错误的agem,我们将用PUT请求测试来更正它。

现在,我们将通过介绍PUT和DELETE服务来完成这个项目的最后一部分。

步骤8、现在,首先停止服务器,按照步骤4,分别添加两个控制器类StudentUpdateController和StudentDeleteController,分别用于PUT和DELETE服务,并修改这两个类,如下所示:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using System.Text;
using StudentRegistrationDemo3.Models;
namespace StudentRegistrationDemo3.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class StudentUpdateController : Controller
{
// GET: api/<controller>
[HttpPut]
public JsonResult UpdateStudentRecord( Student stdn)
{
Console.WriteLine("In updateStudentRecord");
return Json(StudentRegistration.getInstance().UpdateStudent(stdn));
}
}
}
/<controller>

And:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using StudentRegistrationDemo3.Models;
namespace StudentRegistrationDemo2.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class StudentDeleteController : Controller
{
[Route("student/remove/{regdNum}")]
// DELETE: api/<controller>
[HttpDelete]
public IActionResult DeleteStudentRecord(String regdNum)

{
Console.WriteLine("In deleteStudentRecord");
return Ok(StudentRegistration.getInstance().Remove(regdNum));
}
}
}
/<controller>

现在,保存项目并再次启动应用程序,插入三个记录,其中一个记录的年龄值错误,以便我们可以使用PUT服务来纠正它。

步骤9:插入三条记录后,使用下面的URL进行PUT请求测试。在这里,选择PUT方法。

http://localhost:63662/api/studentupdate


ASP.NET Core RESTful Web服务开发教程


现在用GET调用验证更新的记录。

ASP.NET Core RESTful Web服务开发教程


现在是测试我们的最后一个服务DELETE请求的时候了。使用下面的URL并从列表中删除一条记录。另外,我们还可以看看我们是如何在控制器类StudentDeleteController中设计资源路径的。

http://localhost63662/api/studentdelete/student/remove/12346

ASP.NET Core RESTful Web服务开发教程


最后检查结果:

ASP.NET Core RESTful Web服务开发教程



分享到:


相關文章: