1 回答
TA贡献1797条经验 获得超6个赞
鉴于您在编译时知道什么时候知道 snake_case 以及什么时候需要默认策略,您可以这样做:
private Task<object> PostAsync<T1, T2>(string uri, T2 content)
{
return PostAsync<T1, T2>(uri, content, new DefaultNamingStrategy());
}
private async Task<object> PostAsync<T1, T2>(string uri, T2 content, NamingStragy namingStrategy)
{
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 deserializerSettings = new JsonSerializerSettings
{
ContractResolver = new DefaultContractResolver
{
NamingStrategy = namingStrategy
}
};
T1 responseModel = JsonConvert.DeserializeObject<T1>(await response.Content.ReadAsStringAsync(), deserializerSettings);
return responseModel;
}
else
{
return await GetFailureResponseModel(response);
}
}
}
}
所以,当你需要默认策略时:
await PostAsync<Some1, Some2>(uri, some2Content);
并且,当你需要 snake_case 时:
await PostAsync<Some1, Some2>(uri, some2Content, new SnakeCaseNamingStrategy());
- 1 回答
- 0 关注
- 84 浏览
添加回答
举报