1. 概述
REST(Representational State Transfer)是一种软件架构风格,它允许应用程序通过 HTTP 请求来创建、读取、更新和删除数据。RESTful 服务是一种遵循 REST 架构风格的 Web 服务,它允许应用程序通过 HTTP 请求来操作数据,而无需考虑数据的存储结构和访问方式。
2. 创建 ASP.NET RESTful 服务
创建一个 ASP.NET RESTful 服务非常简单,只需要在项目中安装 Microsoft.AspNetCore.Mvc.WebApiCompatShim 包,然后在项目中创建 Web API 控制器即可。
Install-Package Microsoft.AspNetCore.Mvc.WebApiCompatShim
public class ProductsController : Controller
{
private readonly IProductsRepository _productsRepository;
public ProductsController(IProductsRepository productsRepository)
{
_productsRepository = productsRepository;
}
[HttpGet]
public IEnumerable<Product> GetProducts()
{
return _productsRepository.GetAll();
}
[HttpGet("{id}")]
public Product GetProduct(int id)
{
return _productsRepository.GetById(id);
}
[HttpPost]
public Product CreateProduct([FromBody] Product product)
{
return _productsRepository.Create(product);
}
[HttpPut("{id}")]
public Product UpdateProduct(int id, [FromBody] Product product)
{
return _productsRepository.Update(id, product);
}
[HttpDelete("{id}")]
public void DeleteProduct(int id)
{
_productsRepository.Delete(id);
}
}
3. 处理 HTTP 请求和响应
ASP.NET RESTful 服务可以通过重写 Web API 控制器中的方法来处理 HTTP 请求和响应。
public class ProductsController : Controller
{
private readonly IProductsRepository _productsRepository;
public ProductsController(IProductsRepository productsRepository)
{
_productsRepository = productsRepository;
}
[HttpGet]
public IEnumerable<Product> GetProducts()
{
return _productsRepository.GetAll();
}
[HttpPost]
public Product CreateProduct([FromBody] Product product)
{
return _productsRepository.Create(product);
}
[HttpPut("{id}")]
public Product UpdateProduct(int id, [FromBody] Product product)
{
return _productsRepository.Update(id, product);
}
[HttpDelete("{id}")]
public void DeleteProduct(int id)
{
_productsRepository.Delete(id);
}
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
// Handle HTTP Request
if (filterContext.HttpContext.Request.Method == "OPTIONS")
{
filterContext.HttpContext.Response.Headers.Add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
filterContext.HttpContext.Response.Headers.Add("Access-Control-Allow-Headers", "Content-Type, Authorization");
filterContext.HttpContext.Response.StatusCode = 200;
filterContext.Result = new EmptyResult();
return;
}
// Handle CORS
if (filterContext.HttpContext.Request.Headers.ContainsKey("Origin"))
{
filterContext.HttpContext.Response.Headers.Add("Access-Control-Allow-Origin", "*");
}
}
}
4. 使用 JSON 和 XML 来格式化数据
ASP.NET RESTful 服务可以使用 JSON 和 XML 两种格式来格式化数据。
public class ProductsController : Controller
{
private readonly IProductsRepository _productsRepository;
public ProductsController(IProductsRepository productsRepository)
{
_productsRepository = productsRepository;
}
[HttpGet]
public IEnumerable<Product> GetProducts()
{
return _productsRepository.GetAll();
}
[HttpPost]
public Product CreateProduct([FromBody] Product product)
{
return _productsRepository.Create(product);
}
[HttpPut("{id}")]
public Product UpdateProduct(int id, [FromBody] Product product)
{
return _productsRepository.Update(id, product);
}
[HttpDelete("{id}")]
public void DeleteProduct(int id)
{
_productsRepository.Delete(id);
}
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
// Handle HTTP Request
if (filterContext.HttpContext.Request.Method == "OPTIONS")
{
filterContext.HttpContext.Response.Headers.Add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
filterContext.HttpContext.Response.Headers.Add("Access-Control-Allow-Headers", "Content-Type, Authorization");
filterContext.HttpContext.Response.StatusCode = 200;
filterContext.Result = new EmptyResult();
return;
}
// Handle CORS
if (filterContext.HttpContext.Request.Headers.ContainsKey("Origin"))
{
filterContext.HttpContext.Response.Headers.Add("Access-Control-Allow-Origin", "*");
}
// Handle JSON and XML Serialization
var requestContentType = filterContext.HttpContext.Request.ContentType;
if (requestContentType != null && requestContentType.Contains("application/json"))
{
filterContext.HttpContext.Request.ContentType = "application/json; charset=utf-8";
}
else if (requestContentType != null && requestContentType.Contains("application/xml"))
{
filterContext.HttpContext.Request.ContentType = "application/xml; charset=utf-8";
}
}
}
5. 使用 Swagger 来生成 API 文档
Swagger 是一种用于生成 API 文档的工具,它可以帮助开发人员快速了解和使用 API 的功能。
Install-Package Swashbuckle.AspNetCore
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "Products API", Version = "v1" });
});
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "Products API V1");
});
}
}
6. 部署 RESTful 服务
ASP.NET RESTful 服务可以通过各种方式部署,包括在 IIS 上部署、在容器中部署、在云平台上部署等。
dotnet publish -c Release
7. 使用 Postman 来测试 RESTful 服务
Postman 是一款强大的 API 测试工具,它可以帮助开发人员快速测试和调试 API 的功能。