1. 概述 REST(Representational State Transfer)是一种软件架构风格,它允许应用程序通过 Http 请求来创建、读取、更新和删除数据。RESTful 服务是一种遵循 REST 架构风格的 WEB 服务
REST(Representational State Transfer)是一种软件架构风格,它允许应用程序通过 Http 请求来创建、读取、更新和删除数据。RESTful 服务是一种遵循 REST 架构风格的 WEB 服务,它允许应用程序通过 HTTP 请求来操作数据,而无需考虑数据的存储结构和访问方式。
创建一个 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);
}
}
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", "*");
}
}
}
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";
}
}
}
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");
});
}
}
ASP.NET RESTful 服务可以通过各种方式部署,包括在 IIS 上部署、在容器中部署、在云平台上部署等。
dotnet publish -c Release
Postman 是一款强大的 API 测试工具,它可以帮助开发人员快速测试和调试 API 的功能。
--结束END--
本文标题: 从初学者到专家:ASP.NET RESTful 服务开发教程
本文链接: https://lsjlt.com/news/560840.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
2023-05-21
2023-05-21
2023-05-21
2023-05-21
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0