[英]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.