【问题标题】:Why I don't see properties of the response class on the client?为什么我在客户端上看不到响应类的属性?
【发布时间】:2021-04-11 03:44:09
【问题描述】:

我在我的项目中使用 .net core 5。

我有这个api方法:

    [HttpGet]
    public async Task<NumberValidationResponse> CheckNumberAsync(String number)
    {
        try
        {
            var result = await _service.someMethodn(number);
            return result;
        }
        catch (Exception ex) 
        {
            _logger.LogInformation(ex.InnerException.ToString());  //write to file or database
            return new NumberValidationResponse(null, false, "An error occurred, contact administrator.");
        }
    }
    

如您所见,API 方法的返回类型为 Task。

这里是 NumberValidationResponse 定义:

    public class NumberValidationResponse : BaseResponse
    {
        private string Number { get; set; }
        private bool Success { get; set; }

        public NumberValidationResponse(string number, bool isPositive, string message) : base(message) 
        {
            Number = number;
            Success = isPositive;
        }
    }

    public abstract class BaseResponse
    {
        public string Message { get; set; }

        public BaseResponse(string message)
        {
            Message = message;
        }
    }
    

CheckNumberAsync 中的_service.someMethod 返回 NumberValidationResponse 类型,其值为 number、success 和 message。 我希望在客户端上看到相同的值,但在客户端中,我只看到 message 属性的值。

为什么我只看到 NumberValidationResponse 类的消息值,而在客户端看不到该类的其他属性?

【问题讨论】:

  • 这可能是一个错字 - 但你的构造函数和输入 catch 块是 PhoneNumberValidationResponse() 但类名是 NumberValidationResponse()。如果这不是问题 - 必须有更多的东西......否则,完整的 NumberValidationResponse 会出现在客户端

标签: c# asp.net-core asp.net-web-api


【解决方案1】:

NumberSuccessprivate 更改为 public

默认情况下,私有成员不会序列化到响应中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-03-13
    • 2022-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-27
    相关资源
    最近更新 更多