c# - 响应序列化问题

标签 c# asp.net-core

我遇到了一个奇怪的问题,也许我在这里做错了什么。所以我正在使用 .Net Core 2.2 开发 WebApi 项目。我从另一台服务器调用 Api,并将响应解析到该模型中。

 public class LoginResponseModel
{
    [JsonProperty(PropertyName = "token_type")]
    public string tokenType { get; set; }

    [JsonProperty(PropertyName = "access_token")]
    public string accessToken { get; set; }

    [JsonProperty(PropertyName = "expires_in")]
    public string expiresIn { get; set; }

    [JsonProperty(PropertyName = "refresh_token")]
    public string refreshtToken { get; set; }
}

从上面的模型中,您可以从 Api 中看到我在 SnakeCase 中得到响应,我的模型参数在 CamelCase 中。当我反序列化我的 Api 响应时:

 T1 responseModel = JsonConvert.DeserializeObject<T1>(await response.Content.ReadAsStringAsync());

这里的T1LoginResponseModel 它成功地解析了我模型中的 Api Response,请参见随附的屏幕截图, enter image description here

但是当我调用我的 Api 时,它正在调用另一个我刚刚解析其响应的 API(以上示例),返回的响应在 SnakeCase 中。见截图 enter image description here

澄清 只是为了澄清移动应用程序调用我的 Api 即 Login() 而不是我的 Login 方法从另一台服务器调用另一个 Api 即 AuthenticateUser(...)。因此,AuthenticateUser 的响应是 SnakeCase,我正在将其解析到我的 LoginResponseModel 中,然后该响应作为 Login api 响应返回。但是我得到的回应是 SnakeCase

有人可以告诉我我在这里缺少什么或者可以做些什么来解决这个问题。我不想使用另一个模型来转换为我想要的响应。

更新 @Darkonekt Answer 帮助了我,但现在我在序列化和反序列化中面临另一个问题。所以这是我的 PostAsync

通用方法
private async Task<object> PostAsync<T1,T2>(string uri, T2 content)
    {
        using (var requestMessage = new HttpRequestMessage(HttpMethod.Post, uri))
        {
            var json = JsonConvert.SerializeObject(content);
            using (var stringContent = new StringContent(json, Encoding.UTF8, "application/json"))
            {
                requestMessage.Content = stringContent;

                HttpResponseMessage response = await _client.SendAsync(requestMessage);
                if (response.IsSuccessStatusCode)
                {
                    _logger.LogInformation("Request Succeeded");
                    var dezerializerSettings = new JsonSerializerSettings
                    {
                        ContractResolver = new DefaultContractResolver
                        {
                            NamingStrategy = new SnakeCaseNamingStrategy()
                        }
                    };
                    T1 responseModel = JsonConvert.DeserializeObject<T1>(await response.Content.ReadAsStringAsync(), dezerializerSettings);
                    return  responseModel;
                }
                else
                {
                    return await GetFailureResponseModel(response);

                }
            }
        }
    }

因为这个方法是通用的,将用于任何其他 Post 请求,但是在这里我将 Deserializer 设置为 SnakeCase,当 api 响应在 SnakeCase 中时它工作正常,但是当我的其他 Post 请求返回响应在 CamelCase 中时出现问题.由于解析失败,我得到 Null 值。我该如何解决这个问题。

最佳答案

[JsonProperty(PropertyName = "refresh_token")] 属性是一条双向街道。

它在序列化和反序列化时应用。

如果您想在序列化时使用不同的名称,您将需要 ContractResolver 和您自己的设置。

查看这个 stackoverflow 问题,详细了解如何操作:Serialize and Deserialize with different property names

或者您需要创建两个模型,一个用于序列化,一个用于反序列化,并在它们之间进行映射,然后返回没有属性的模型。

关于c# - 响应序列化问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55764281/

相关文章:

c# - 通过样式 block 解析 Open XML 文档

C# 串行端口线程,一段时间后应用程序崩溃

asp.net-core - 如何使用 EFCore Code First Migrations 指定复合主键

c# - 在Select中调用heavy方法可以吗?

c# - DataGridView 列中的计算

c# - 值必须是小于无穷大的数字

c# - 覆盖asp.net core 1.1中的现有数据注释属性

c# - ASP.NET Core 2 - 身份 - 自定义角色的 DI 错误

asp.net-core - IWebHost WebHostBuilder BuildWebHost 有什么区别

angularjs - ASP.NET Core API - 登录和防伪 token