ASP.NET Core 3 高级编程(第8版) 学习笔记 04

devtools/2024/9/23 6:37:27/

第 19 章主要介绍 Restful Service 的相关知识。Restful Service 的核心内容是:(1)HTTP 请求或 HTTP 动词,用 HTTP 请求表达不同的操作,最好遵守惯例。(2)资源,通过 PATH 结合 payload 来表达。以本章的示例来说:

请添加图片描述

除 Restful Service 外,替代品包括 GraphQL 和 gRPC。

使用自定义的端点实现 Web Service

不同语言的 Web 框架,都需要解决 Routing 问题,也就是客户端提交的请求,服务器通过内部机制最终处理的方法或者函数。在 asp.net core 中,比较流程的方法就是实用 MVC 来实现路由。但在使用标准的 MVC 框架之前,本书介绍了通过自定义 endpoint 来实现的方法。结合第 18 章,也就是说解决路由问题可以有 3 种方法:
1)使用中间件
2)自定义 endpoint
3)使用 MVC 框架的 Controller

第一步:新建 WebserviceEndpoint 类,在该类中实现了获取所有 products,根据 id 获取 product 和创建一个新的 product 三个功能:

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.DependencyInjection;
using System.Collections;
using System.Collections.Generic;
using System.Text.Json;
using WebApp.Models;namespace WebApp
{public static class WebServiceEndpoint{private static string BASE_URL = "api/products";public static void MapWebService(this IEndpointRouteBuilder app){// 匹配 GET: /api/products/{id}app.MapGet($"{BASE_URL}/{{id}}", async context =>{long key = long.Parse(context.Request.RouteValues["id"] as string);DataContext dbContext = context.RequestServices.GetService<DataContext>();var p = dbContext.Products.Find(key);if (p == null) {context.Response.StatusCode = StatusCodes.Status404NotFound;} else {context.Response.ContentType = "application/json";context.Response.StatusCode = StatusCodes.Status200OK;await context.Response.WriteAsync(JsonSerializer.Serialize<Product>(p));}});app.MapGet(BASE_URL, async context => {DataContext dbContext = context.RequestServices.GetService<DataContext>();context.Response.ContentType = "application/json";await context.Response.WriteAsync(JsonSerializer.Serialize<IEnumerable<Product>>(dbContext.Products));});app.MapPost(BASE_URL, async context => {DataContext dbContext = context.RequestServices.GetService<DataContext>();Product p = await JsonSerializer.DeserializeAsync<Product>(context.Request.Body);await dbContext.AddAsync(p);await dbContext.SaveChangesAsync();context.Response.StatusCode=StatusCodes.Status200OK;});}}
}

注意 MapService() 方法是 IEndpointRouteBuilder 的扩展方法

第二步:在 Startup 类的 Configure() 方法中注册服务:

测试自定义端点

测试建议使用流行的工具,比如 Postman,而不是使用书中所介绍的 Invoke-ReestMethod 等工具。打开 Postman,对自定义 endpoint 的 3 个功能进行测试:

提交后,在数据库中查看:

使用控制器创建 Web 服务

第一步:在 Startup 类的 ConfigureService() 方法中,将控制器的服务添加到指定的 IServiceCollection,并且在 Configure() 中,通过 endpoints.MapControllers(); 方法实现默认的路由。

第二步:创建 Controller ,定义 Action 方法。XXXController 从 ControllerBase 类派生

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using WebApp.Models;namespace WebApp.Controllers
{[Route("api/[controller]")][ApiController]public class ProductsController : ControllerBase{private DataContext dbContext;public ProductsController(DataContext dbContext){this.dbContext = dbContext;}// Get products[HttpGet]public IEnumerable<Product> GetProducts(){return dbContext.Products;}// Get product by Id[HttpGet("{id}")]public Product GetProduct(){return dbContext.Products.FirstOrDefault();}// Create product[HttpPost]public void SaveProduct([FromBody]Product p){dbContext.Products.Add(p);dbContext.SaveChanges();}}
}

Controller 实现了相同的功能,我们可以从中看到框架的好处。

源码

pro asp.net core 3 notes: 《ASP.NET Core 3高级编程(第8版)》学习笔记


http://www.ppmy.cn/devtools/12840.html

相关文章

React 19 的新增功能:Action Hooks

React 是前端开发领域最流行的框架之一。我喜欢 React 是因为它背后的团队和社区对它的热情。当社区提出新功能和改进的需求时,团队会倾听,React 的未来是令人兴奋和有趣的。 让我们来看一下 React 19 中令开发人员提升开发效率的新特性。对于每个钩子,我将解释它的作用并给…

XGBoost原生接口和Sklearn接口参数详解

XGBoost原生接口和Sklearn接口参数详解 数据科学&#xff1a;Scipy、Scikit-Learn笔记超参数调优&#xff1a;网格搜索&#xff0c;贝叶斯优化&#xff08;optuna&#xff09;详解LightGBM原生接口和Sklearn接口参数详解XGBoost一、Sklearn风格接口xgboost.XGBRegressor参数一般…

『docker』 容器虚拟化技术之空间隔离实战

文章目录 容器虚拟化基础之 NameSpaceNameSpace 隔离实战实战目的基础知识dd 命令详解mkfs 命令详解df 命令详解mount 命令详解unshare 命令详解 实战操作一&#xff08;PID 隔离&#xff09;实战操作二&#xff08;Mount 隔离&#xff09; 容器虚拟化基础之 NameSpace 什么是…

DTU如何用VPN

在工业物联网的应用中&#xff0c;数据传输单元&#xff08;DTU&#xff09;作为关键的通信设备&#xff0c;承担着现场设备与远程服务器之间的数据传输任务。然而&#xff0c;在某些情况下&#xff0c;由于网络环境的限制或安全需求&#xff0c;我们需要通过虚拟私人网络&…

Redis篇:实现短信登录

实现的是黑马点评的手机号短信验证码登录功能 1.实现流程 发送验证码&#xff1a; 用户在提交手机号后&#xff0c;会使用正则表达式校验手机号是否合法&#xff0c;如果不合法&#xff0c;则要求用户重新输入手机号 如果手机号合法&#xff0c;后台此时生成对应的验证码&a…

算法练习|Leetcode189轮转数组 ,Leetcode56合并区间,Leetcode21合并两个有序链表,Leetcode2两数相加,sql总结

目录 一、Leetcode189轮转数组题目描述解题思路方法:切片总结 二、Leetcode56合并区间题目描述解题思路方法:总结 三、Leetcode21合并两个有序链表题目描述解题思路方法:总结 四、Leetcode2两数相加题目描述解题思路方法:总结 sql总结: 一、Leetcode189轮转数组 题目描述 给定…

python基本语法与使用

Python是一种高级编程语言&#xff0c;它被广泛应用于各种领域&#xff0c;包括Web开发、数据科学、人工智能等。以下是Python的基本语法和使用方法&#xff1a; 1.注释 使用#来添加单行注释&#xff0c;多行注释可以使用或"""来包围。 # 这是一个单行注释…

怎么选出一个95分的产品?选品的逻辑到底是什么?如何不选错

大家好&#xff0c;我是电商花花。 选品定生死。 做电商的应该都会听过这句话&#xff0c;可能有些商家也只是听听就过去&#xff0c;如果没有遇到选品的问题就很难感受到。 如果你体验到一款好的产品带来的流量红利&#xff0c;体验一次爆单&#xff0c;就会知道选出优质的…