.NET Core 6 Blazor:如何仅通过URI传递参数调用服务器实现数据记录单属性修改
在Blazor中优雅实现服务器端RPC式计数器修改
好问题!这种只需要通过路由ID触发服务器端修改、不需要传递客户端数据的场景,确实有比传null更优雅的实现方式,下面给你几个实用的方案:
方案1:用HttpGet调用(注意幂等性场景)
如果你的计数器增减操作是幂等的(比如重复调用不会产生意外副作用,不过加1操作本身是非幂等的,需要结合业务场景判断),可以直接用GetAsync,完全不需要传递任何内容参数,代码看起来清爽很多:
服务器端(Minimal API示例)
// Program.cs 中配置端点 app.MapGet("/api/watermark/addreference/{id}", async (Guid id, AppDbContext db) => { var targetRecord = await db.Watermarks.FindAsync(id); if (targetRecord == null) return Results.NotFound(); // 执行计数器增减操作 targetRecord.ReferenceCount++; await db.SaveChangesAsync(); return Results.Ok(); });
Blazor客户端调用
public static async Task<bool> AddReference(Guid ID) { HttpResponseMessage response = await httpClient.GetAsync(Routes.WatermarkApi + $"AddReference/{ID}"); return response.IsSuccessStatusCode; }
注意:HTTP规范里Get方法应仅用于获取数据而非修改数据,所以如果你的操作会改变服务器状态(比如计数器加1),更推荐用下面的Post方案,避免缓存或重复请求带来的问题。
方案2:PostAsync传递空的合法Content(规范且优雅)
不想传null,可以传递一个空的StringContent,既符合Post请求的协议要求,又不会显得别扭:
Blazor客户端调用
public static async Task<bool> AddReference(Guid ID) { // 传递空的JSON内容,符合请求体格式要求 var emptyContent = new StringContent(string.Empty, Encoding.UTF8, "application/json"); HttpResponseMessage response = await httpClient.PostAsync(Routes.WatermarkApi + $"AddReference/{ID}", emptyContent); return response.IsSuccessStatusCode; }
服务器端(Controller示例)
[ApiController] [Route("api/[controller]")] public class WatermarkController : ControllerBase { private readonly AppDbContext _dbContext; public WatermarkController(AppDbContext dbContext) { _dbContext = dbContext; } [HttpPost("AddReference/{id}")] public async Task<IActionResult> AddReference(Guid id) { var targetRecord = await _dbContext.Watermarks.FindAsync(id); if (targetRecord == null) return NotFound(); targetRecord.ReferenceCount++; await _dbContext.SaveChangesAsync(); return Ok(); } }
方案3:利用Minimal API简化Post端点
如果用Minimal API,甚至可以直接定义不需要请求体的Post端点,和Get写法几乎一样,但语义上更符合修改操作:
// Program.cs 中配置端点 app.MapPost("/api/watermark/addreference/{id}", async (Guid id, AppDbContext db) => { var targetRecord = await db.Watermarks.FindAsync(id); if (targetRecord == null) return Results.NotFound(); targetRecord.ReferenceCount++; await db.SaveChangesAsync(); return Results.Ok(); });
客户端还是用方案2的PostAsync传递空Content即可,这样既遵循了HTTP语义,又保持了代码的优雅性。
内容的提问来源于stack exchange,提问作者Razzupaltuff
相关产品推荐
相关产品推荐

