如何在 .net 核心中将字符串响应(文本)转换为 JSON 响应

How to convert String response (Text) to JSON response in .net core

我需要将字符串响应转换为 Json 响应。但是我必须使用不同的方法来解决我的问题,但我找不到任何好的解决方案。

if (response.IsSuccessStatusCode)
{
    string successResponse = "Order Created Successfully with InterfaceRecordId : " + order.WMWDATA.Receipts.Receipt.InterfaceRecordId + " & ReceiptId : " +
      order.WMWDATA.Receipts.Receipt.ReceiptId;
    _logger.LogInformation(successResponse);
    return StatusCode((int)response.StatusCode, successResponse);
}
_logger.LogError(jsonResponse);
return StatusCode((int)response.StatusCode, jsonResponse);

我只需要将此 successRespose 作为 JSON 响应发送。你能帮我解决这个问题吗?

请阅读 Format response data in ASP.NET Core Web API。有多种可能性,具体取决于您的具体要求。

最简单的选择是将 [Produces] 属性添加到控制器操作,指定从 aciton returned 的类型:

[Produces("application/json")]
public IActionResult YourAction(int id) { ... }

即使 return 类型的操作是 string.

,上述操作也会 return application/json

但是,看起来您正在 return 字符串中的两个值(InterfaceRecordIdReceiptId)。您可以使用 built-in 方法(例如 Ok()BadRequest()Created()NotFound() 等)将对象转换为 JSON 和 return一个特定的状态码。

我建议 returning 包含两个值的对象,并使用方便的 return 方法(Created()CreatedAtAction())。以下 return 是一个匿名对象和状态代码 201:

var successResponse = new 
{ 
    InterfaceRecordId = order.WMWDATA.Receipts.Receipt.InterfaceRecordId,
    ReceiptId = order.WMWDATA.Receipts.Receipt.ReceiptId
}

return CreatedAtAction(nameof(YourAction), successResponse); 

CreatedAtAction(和Created)便捷方法return 201(已创建)HTTP 代码 - 因此客户端将能够从状态代码中推断出来。由于它是 returning 对象(而不是字符串),return 类型默认为 application/json,因此不需要 [Produces] 属性。