C# Azure Functions中OkObjectResult未返回JSON仅返回对象类型名问题
问题根因
当前接口返回类型名而非对象JSON结构的核心原因有两个:
- 直接使用字符串插值
$"Successfully executed {accessabilityResult}"拼接对象时,C#会默认调用对象的ToString()方法,由于AccessibilityErrorOutput类没有重写ToString()方法,默认返回对象的全限定类型名。 - 接口OpenApi配置标注返回类型为
text/plain纯文本,运行时不会对传入内容做对象JSON序列化处理。
修复步骤
- 修改OpenApi响应特性配置,将响应内容类型改为
application/json,匹配JSON返回格式。 - 构造包含提示文本和结果对象的复合响应载体,传入
OkObjectResult,Functions运行时会自动将整个对象序列化为标准JSON结构返回。
修改后完整代码示例
public class AccCheckerForOpenXML { private readonly ILogger<AccCheckerForOpenXML> logger; public AccCheckerForOpenXML(ILogger<AccCheckerForOpenXML> log) => this.logger = log; /// <summary> /// Function that receives a httptrigger and then starts processing documents the Office Open XML files. /// </summary> [FunctionName("AccCheckerForOpenXML")] [OpenApiOperation(operationId: "Run", tags: new[] { "docName" })] [OpenApiParameter(name: "name", In = ParameterLocation.Query, Required = true, Type = typeof(string), Description = "The **Name** parameter")] // 修改响应配置:contentType改为application/json,bodyType改为object [OpenApiResponseWithBody(statusCode: HttpStatusCode.OK, contentType: "application/json", bodyType: typeof(object), Description = "The OK response")] public async Task<IActionResult> Run( [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req) { this.logger.LogInformation("AccCheckerForDocx: Run method:HTTP trigger -- function processed a request."); string filePath = req.Query["name"]; var requestBody = await new StreamReader(req.Body).ReadToEndAsync(); dynamic data = JsonConvert.DeserializeObject(requestBody); filePath ??= data?.name; // Http Response if (filePath == null) { return new BadRequestObjectResult("Did not execute. Please include the file path"); } else { var accessabilityResult = await DocumentProcessor.ProcessDocumentMainAsync(filePath, this.logger); // 返回匿名对象作为响应载体,包含提示信息和结果数据 return new OkObjectResult(new { Message = "Successfully executed", Data = accessabilityResult }); } } }
返回效果
接口正常返回200状态码,响应内容为标准JSON格式,结构如下:
{ "Message": "Successfully executed", "Data": { // 此处为accessabilityResult对象所有属性序列化后的内容 } }
如果你有特殊需求必须返回纯文本格式而非JSON结构,可以手动序列化
accessabilityResult后再拼接字符串:string resultJson = JsonConvert.SerializeObject(accessabilityResult); return new OkObjectResult($"Successfully executed\n{resultJson}");但这种方式不符合REST接口规范,客户端解析成本更高,优先推荐返回结构化JSON的方案。
内容的提问来源于stack exchange,提问作者Coco
相关产品推荐
相关产品推荐

