我有一个简单的 ASP.NET Core 7 Web API 方法:
[HttpPost("processPiece")]
public async Task<ActionResult<string>> ProcessPiece([FromBody] PieceModel piece)
{
return _processingService.ProcessPiece(piece.Piece);
}
ProcessPiece
方法返回一个字符串值。它包含多行。
我正在尝试在 UI 上的 Blazor 组件中显示此值。
_httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var response = await _httpClient.PostAsync($"api/Piece/processPiece", new StringContent("{\"piece\":\"" + piece + "\"}", Encoding.UTF8, "application/json"));
return await response.Content.ReadAsStringAsync();
视图标记现在非常简单:
<p>@outputValue</p>
我发现
response.Content.ReadAsStringAsync();
返回用额外引号括起来的字符串,而不是渲染新行,而是显示 \r\n
。
输出在传输或解码过程中似乎以某种方式转义了。
我在这里寻找解决方案,但我发现的有关该主题的所有线程似乎都至少有 10 年历史,并且提供的解决方案似乎不起作用。
无论如何,我已经尝试通过将端点返回的类型切换为纯文本来实现建议的解决方案之一:
[HttpPost("processPiece")]
public async Task<ActionResult<HttpResponseMessage>> ProcessPiece([FromBody] PieceModel piece)
{
var a = _processingService.ProcessPiece(piece.Piece);
var resp = new HttpResponseMessage(HttpStatusCode.OK);
resp.Content = new StringContent(a, System.Text.Encoding.UTF8, "text/plain");
return resp;
}
客户端:
_httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("text/plain"));
var response = await _httpClient.PostAsync($"api/Piece/processPiece", new StringContent("{\"piece\":\"" + piece + "\"}", Encoding.UTF8, "application/plaintext"));
var a = await response.Content.ReadAsStringAsync();
return a;
这根本不起作用。现在我从端点获得的只是一堆元数据:
{"version":"1.1","content":{"headers":[{"key":"Content-Type","value":["text/plain; charset=utf-8"]}]},"statusCode":200,"reasonPhrase":"OK","headers":[],"trailingHeaders":[],"requestMessage":null,"isSuccessStatusCode":true}
有人可以帮忙吗?
ASP.NET Core 不会将
HttpResponseMessage
作为特殊类型处理,因此您的结果将被序列化为 JSON。只需使用 Content
选项之一。例如:
public async Task<IActionResult> ProcessPiece([FromBody] PieceModel piece)
{
return Content(a, "text/plain", System.Text.Encoding.UTF8);
}
或通过
Results
/TypedResults
(取决于用例)。