[英]Returning custom HttpResponseMessage as IActionResult
[英]IActionResult not returning string response as string
我正在将我的 web api 迁移到 .net 核心代码。
这是我当前的 api,它按预期正确返回字符串
[HttpPost]
public string ValidateEwpInspectionNumber(string ewpNumber, string inspectionNumber)
{
return _ewpDataAccess.ValidateEwpInspectionNumber(ewpNumber, inspectionNumber);
}
这就是响应在开发者工具中的样子
这是我的代码所期望的。 api 正确返回字符串结果。
现在,这是我们使用IActionResult
作为返回类型的迁移 api
[HttpPost(nameof(ValidateEwpInspectionNumber))]
[ProducesResponseType(typeof(string), StatusCodes.Status200OK)]
public async Task<IActionResult> ValidateEwpInspectionNumber(string ewpNumber, string inspectionNumber)
{
var response = await _ewpBusinessService.ValidateEwpInspectionNumberAsync(ewpNumber, inspectionNumber);
return Ok(response);
}
但是这个 api 没有将结果作为字符串返回。 这就是响应的样子。
您可以看到它与旧的 api 不同,因此角度代码不将响应视为字符串而是一个对象。
我也尝试返回Content(response)
和Content(response, 'text/plain')
但那也返回了相同类型的对象。
尝试用ActionResult<string>
替换IActionResult
,但没有成功。
有什么方法可以像旧 api 返回的那样从IActionResult
返回直接字符串吗?
更新
我检查了默认情况下Ok()
仅返回我想要的 json 格式的响应,但是对于我的响应,因为它是纯文本,所以它将内容类型设置为text/plain
。
所以我尝试使用Content(response, 'application/json')
手动设置内容类型,但随后它开始出现 json 解析错误
无法解析 JSON。 原始结果:
不存在
所以看起来 .net 核心 api 不可能将字符串作为 json 返回,直到它实际上是一个有效的 json。
你能检查一下 API 响应是 JSON 还是只是文本吗? 您共享的屏幕截图似乎响应格式为纯文本,而旧 api 的响应格式为 JSON。 如果是这种情况,您可能希望强制 API 返回 JSON。
将其作为JsonResult
返回,您需要对其进行格式化:
public async Task<IActionResult> ValidateEwpInspectionNumber(string ewpNumber, string inspectionNumber)
{
var response = await _ewpBusinessService.ValidateEwpInspectionNumberAsync(ewpNumber, inspectionNumber);
return new JsonResult(response);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.