You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET Core 7 Web API纯文本响应及Blazor渲染问题求助

解决方案

方案1:保持JSON序列化,正确解析返回值

你的第一个API写法本身没问题,问题出在客户端没有正确解析JSON格式的返回结果。ReadAsStringAsync()拿到的是JSON序列化后的字符串(自带引号、换行符被转义为"\r\n"),需要反序列化还原原始内容。

修改客户端代码:

_httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var response = await _httpClient.PostAsync($"api/Piece/processPiece", 
    new StringContent($"{{\"piece\":\"{piece}\"}}", Encoding.UTF8, "application/json"));
// 反序列化去掉JSON的引号和转义字符
var jsonString = await response.Content.ReadAsStringAsync();
var rawOutput = System.Text.Json.JsonSerializer.Deserialize<string>(jsonString);
return rawOutput;

Blazor视图中要让换行生效,有两种方式:

<!-- 方式1:将换行符替换为HTML换行标签 -->
<p>@(outputValue?.Replace("\r\n", "<br>"))</p>

<!-- 方式2:用<pre>标签保留原始文本格式 -->
<pre>@outputValue</pre>

方案2:直接返回纯文本(推荐)

不要返回ActionResult<HttpResponseMessage>,ASP.NET Core中返回纯文本直接用Content()方法即可,避免序列化元数据的问题。

修改API代码:

[HttpPost("processPiece")]
public async Task<IActionResult> ProcessPiece([FromBody] PieceModel piece)
{
    var result = _processingService.ProcessPiece(piece.Piece);
    return Content(result, "text/plain", Encoding.UTF8);
}

客户端代码调整:

// 声明接受纯文本响应
_httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("text/plain"));
// 请求体仍需用application/json,因为API用[FromBody]绑定JSON格式模型
var response = await _httpClient.PostAsync($"api/Piece/processPiece", 
    new StringContent($"{{\"piece\":\"{piece}\"}}", Encoding.UTF8, "application/json"));
var rawOutput = await response.Content.ReadAsStringAsync();
return rawOutput;

Blazor视图同样用<pre>标签或替换换行符的方式显示即可。

关键注意点

客户端请求体的Content-Type必须保持application/json,因为API的[FromBody]特性仅支持JSON格式的请求绑定,改成其他类型会导致piece参数绑定失败。

内容的提问来源于stack exchange,提问作者Shaggydog

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 05:23:31