【问题标题】:need to add the Json serialization settings in asp.net core web api controller method需要在asp.net core web api控制器方法中添加Json序列化设置
【发布时间】:2020-11-18 07:13:45
【问题描述】:

如何添加以下 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);
            }
        }

【问题讨论】:

    标签: asp.net json asp.net-core-webapi


    【解决方案1】:

    这就是我可以达到我的要求的方式

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-06-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-17
      • 1970-01-01
      相关资源
      最近更新 更多