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服務開發教程



分享到:


相關文章: