提问人:Shaggydog 提问时间:11/1/2023 最后编辑:Guru StronShaggydog 更新时间:11/4/2023 访问量:81
从 Core 7 Web API 终结点获取纯文本响应 ASP.NET 获取纯文本响应
Getting plaintext response from ASP.NET Core 7 Web API endpoint
问:
我有一个简单的 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}
谁能帮忙?
答:
1赞
Guru Stron
11/1/2023
#1
ASP.NET Core 不作为特殊类型处理,因此您的结果将被序列化为 JSON(因此,如果您只返回一个字符串,它将被编码为 JSON,因此需要额外的引号)。只需使用其中一个选项即可。例如:HttpResponseMessage
Content
public async Task<IActionResult> ProcessPiece([FromBody] PieceModel piece)
{
return Content("somestring", "text/plain", System.Text.Encoding.UTF8);
}
或通过 /(取决于用例)。Results
TypedResults
评论
0赞
Shaggydog
11/1/2023
返回 Content(a, “text/plain”, System.Text.Encoding.UTF8);< - 这里 VS 告诉我内容无法识别,并且它没有提供添加任何“使用”语句。所以我假设这段代码来自某个不同版本的 asp.net?
0赞
Shaggydog
11/1/2023
我尝试了“返回结果.内容...,我得到这个:无法隐式转换类型”Microsoft.AspNetCore.Http.IResult“到”Microsoft.AspNetCore.Mvc.ActionResult”。存在显式转换(是否缺少强制转换?
评论
\r\n
@outputValue