繁体   English   中英

需要在asp.net核心web api controller方法中添加Json序列化设置

[英]need to add the Json serialization settings in asp.net core web api controller method

如何将以下 json 序列化设置:TypeNameHandling = TypeNameHandling.All 添加到响应中,以便将 $type 属性添加到响应 Json..我如何实现

[HttpGet("GetCustomerById")]
[ProducesResponseType(typeof(CustomerBase), StatusCodes.Status200OK)]
      public virtual async Task<ActionResult<CustomerBase>> GetCustomerByIdAsync(int customerId)
        {
            try
            {
                if (customerId<= 0)
                {
                    return BadRequest("Invalid customerId in the request.");
                }

                _logger.LogDebug($"Getting Customer by Id : {CustomerId}");

                using (var scope = _serviceScopeFactory.CreateScope())
                {
                    var customer= await scope.ServiceProvider
                        .GetRequiredService<ICustomerServerApiClient>()
                        .GetCustomerByIdAsync(CustomerId);

                    return Ok(customer);
                }
            }
            catch (Exception ex)
            {
                _logger.LogCritical($"Exception in Get Customer by Id: {CustomerId} " +
                                    $"Returning a 500 to the caller. Exception message: {ex.Message}. " +
                                    $"Stack trace: {ex.StackTrace}.");
                return StatusCode(StatusCodes.Status500InternalServerError, ex.Message);
            }
        }

这就是我如何实现我的要求

//return Ok(customer); replaced by below line
 return new JsonResult(customer) { SerializerSettings = new JsonSerializerSettings() { TypeNameHandling = TypeNameHandling.All } }; 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM