在Azure独立函数中验证HttpRequestData的JSON内容及非空性
Azure HTTP函数验证请求体非空且为JSON类型
要完成请求体非空+JSON格式的验证,需要从请求头检查和内容有效性验证两个层面入手,以下是完整的实现代码:
public async Task<HttpResponseData> Run([HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequestData req) { // 检查请求体非空 if (req.Body.Length == 0) { var nullResponse = req.CreateResponse(HttpStatusCode.BadRequest); await nullResponse.WriteStringAsync("请求体不能为空"); return nullResponse; } // 检查Content-Type是否为JSON类型(兼容带charset的情况,忽略大小写) bool isJsonContentType = req.Headers.TryGetValues("Content-Type", out var contentTypeValues) && contentTypeValues.Any(ct => ct.StartsWith("application/json", StringComparison.OrdinalIgnoreCase)); if (!isJsonContentType) { var invalidContentTypeResponse = req.CreateResponse(HttpStatusCode.UnsupportedMediaType); await invalidContentTypeResponse.WriteStringAsync("请求Content-Type必须为application/json"); return invalidContentTypeResponse; } // 验证请求体是否为有效JSON try { // 重置流位置:检查Length后流指针可能已到末尾,需重置到起始位置才能读取内容 req.Body.Position = 0; using var reader = new StreamReader(req.Body); string bodyContent = await reader.ReadToEndAsync(); // 使用System.Text.Json解析,无效JSON会抛出JsonException JsonDocument.Parse(bodyContent); } catch (JsonException) { var invalidJsonResponse = req.CreateResponse(HttpStatusCode.BadRequest); await invalidJsonResponse.WriteStringAsync("请求体不是有效的JSON格式"); return invalidJsonResponse; } // 此处添加你的业务逻辑 var successResponse = req.CreateResponse(HttpStatusCode.OK); await successResponse.WriteStringAsync("请求验证通过"); return successResponse; }
关键细节说明:
- Content-Type检查:允许带
charset后缀的JSON类型头(比如application/json; charset=utf-8),用StartsWith+忽略大小写的方式匹配,避免漏判。 - 流位置重置:
req.Body.Length的读取会移动流的指针,后续读取内容前必须重置到起始位置,否则会读取到空内容。 - JSON有效性验证:仅靠头检查不够严谨,必须实际解析内容——
JsonDocument.Parse会在遇到无效JSON时抛出JsonException,捕获这个异常即可判定内容无效。
内容的提问来源于stack exchange,提问作者Jason_Hough
相关产品推荐
相关产品推荐

