Asp.net core 如何避免在Web API中对JSON进行反序列化/序列化?
我在ASP.NET 2.0中的Web API控制器中有以下代码:Asp.net core 如何避免在Web API中对JSON进行反序列化/序列化?,asp.net-core,.net-core,Asp.net Core,.net Core,我在ASP.NET 2.0中的Web API控制器中有以下代码: [HttpGet] [Route("{controllerName}/{nodeId}/ConfigurationValues")] public async Task<IActionResult> GetConfigurationValues(string controllerName, byte nodeId, string code) { string payload = ... HttpRes
[HttpGet]
[Route("{controllerName}/{nodeId}/ConfigurationValues")]
public async Task<IActionResult> GetConfigurationValues(string controllerName, byte nodeId, string code)
{
string payload = ...
HttpResponseMessage response = await deviceControllerRepository.ExecuteMethodAsync(controllerName, "GetNodeConfigurationValues", payload);
string responseJson = await response.Content.ReadAsStringAsync();
var configurationValues = JsonConvert.DeserializeObject<List<ConfigurationValue>>(responseJson);
return Ok(configurationValues);
}
[HttpGet]
[路由(“{controllerName}/{nodeId}/ConfigurationValues”)]
公共异步任务GetConfigurationValues(字符串控制器名称、字节节点ID、字符串代码)
{
字符串有效负载=。。。
HttpResponseMessage response=Wait deviceControllerRepository.ExecuteMethodAsync(控制器名称,“GetNodeConfiguration值”,有效负载);
string responseJson=await response.Content.ReadAsStringAsync();
var configurationValues=JsonConvert.DeserializeObject(responseJson);
返回Ok(配置值);
}
如何避免在返回响应JSON之前将其反序列化为.NET对象,因为它已经是正确的JSON格式
我试图将该方法更改为返回HttpResponseMessage,但这导致将不正确的JSON传递回调用方。您可以返回ContentResult而不是Ok(),以避免不必要的序列化:
return new ContentResult
{
Content = responseJson,
ContentType = "application/json",
StatusCode = 200
};
ControllerBase
类有一个用于此目的的Content()
方法。确保在输出数据包中设置了正确的内容类型标头:
return Content(responseJson, "application/json");
deviceControllerRepository做什么?为什么不能将其设置为return object而不是HttpResponseMessage?可以将该字符串写入响应并返回Ok(),而不像现在这样提供参数。@Rob,Ok()将在内容类型标题中发送“text/plain”。我现在不在PC附近,但应该有控制器公开的Json方法。我知道该方法接受一个对象,但您也可以尝试向它传递一个字符串。由于包含引号,它不是有效的json。有一个Content()方法将为您构造ContentResult。