ASP.NET Web API是一個框架,可以輕松構(gòu)建到達各種客戶端(包括瀏覽器和移動設(shè)備)的HTTP服務(wù)。ASP.NET Web API是在.NET Framework上構(gòu)建RESTful應(yīng)用程序的理想平臺。
當(dāng)要Web上構(gòu)建API時,可以通過多種方式在Web上構(gòu)建API。 這些包括HTTP/RPC
,這意味著在遠程過程調(diào)用中使用HTTP來通過Web調(diào)用諸如方法之類的東西。
這些動詞本身包含在API中,例如:獲取客戶,插入發(fā)票,刪除客戶,并且每個這些端點最終都是一個單獨的URI。
下面通過創(chuàng)建一個新的ASP.NET Web應(yīng)用程序來看看如何構(gòu)造一個簡單的Web API示例。
第1步 - 打開Visual Studio,然后單擊:文件 -> 新建 -> 項目 菜單選項。
一個新的項目對話框打開。如下圖所示 -
第2步 - 在左側(cè)窗格中,選擇:模板 -> Visual C# -> Web 。
第3步 - 在中間窗格中,選擇“ASP.NET Web應(yīng)用程序”,在名稱字段中輸入項目名稱:WebAPIDemo ,然后單擊確定 以繼續(xù)。將看到以下對話框,要求您為ASP.NET項目設(shè)置初始內(nèi)容。如下圖所示 -
第4步 - 為了簡單起見,請選擇: 空 選項,并在“為以下項添加文件夾和核心引用” 部分中選中Web API 復(fù)選框,然后單擊 確定 。
第5步 - 它將創(chuàng)建一個基本的MVC項目與最小的預(yù)定義的內(nèi)容。
項目由Visual Studio創(chuàng)建后,在“解決方案資源管理器”窗口中看到許多文件和文件夾。
第6步 - 現(xiàn)在需要添加一個模型。右鍵單擊解決方案資源管理器 中的Models 文件夾,然后選擇:添加 -> 類。將看到添加新項目對話框。
第7步 - 選擇中間平臺的類,并在名稱字段中輸入Employee.cs
。
第8步 - 使用下面的代碼將一些屬性添加到Employee
類。代碼如下所示 -
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace WebAPIDemo.Models
{
public class Employee
{
public int ID { get; set; }
public string Name { get; set; }
public DateTime JoiningDate { get; set; }
public int Age { get; set; }
}
}
第9步 - 添加控制器。右鍵單擊解決方案資源管理器 中的Controllers 文件夾,然后選擇:添加 -> 控制器 。它將顯示“添加基架”對話框 -
第10步 - 選擇:Web API 2控制器 - 空 選項。該模板將為控制器創(chuàng)建一個具有默認(rèn)操作的Index
方法。
第11步 - 點擊“添加”按鈕,添加控制器對話框?qū)⒊霈F(xiàn)。
第12步 - 將名稱設(shè)置為:EmployeesController,然后單擊“添加” 按鈕。
在Controllers
文件夾中看到一個新的 C# 文件 - EmployeeController.cs
,該文件夾在Visual Studio中打開,并進行一些默認(rèn)操作。如下代碼 -
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using WebAPIDemo.Models;
namespace WebAPIDemo.Controllers
{
public class EmployeesController : ApiController
{
Employee[] employees = new Employee[]{
new Employee { ID = 1, Name = "Maxsu", JoiningDate =
DateTime.Parse(DateTime.Today.ToString()), Age = 30 },
new Employee { ID = 2, Name = "Allan", JoiningDate =
DateTime.Parse(DateTime.Today.ToString()), Age = 35 },
new Employee { ID = 3, Name = "AvgWong", JoiningDate =
DateTime.Parse(DateTime.Today.ToString()), Age = 21 }
};
public IEnumerable<Employee> GetAllEmployees()
{
return employees;
}
public IHttpActionResult GetEmployee(int id)
{
var employee = employees.FirstOrDefault((p) => p.ID == id);
if (employee == null)
{
return NotFound();
}
return Ok(employee);
}
}
}
第13步 - 運行這個應(yīng)用程序,并在瀏覽器中訪問URL:http://localhost:58150/api/employees/
,然后按“Enter”。將看到以下輸出 -
第14步 - 再次訪問URL:http://localhost:58150/api/employees/1
,將看到以下輸出 -