问题描述
我创建了一个调用外部 API 的基本控制台应用程序。我的 Main 方法是硬编码用于测试目的:
static void Main(string[] args)
{
// building a login request
LoginRequest loginRequest = new LoginRequest("myLogin","myPassword");
LoginService loginService = new LoginServiceImpl();
LoginResponse loginResponse = loginService.Authenticate(loginRequest);
Console.WriteLine("Authentication tryout!");
Console.WriteLine(">> Token : " + loginResponse.Accesstoken);
Console.WriteLine(">> Type : " + loginResponse.TokenType);
}
我正在将一个对象传递给服务层。在这个类中,我实现了 Authenticate 方法:
public LoginResponse Authenticate(LoginRequest request)
{
LoginResponse returnValue = new LoginResponse();
Uri uri = new Uri("http://www.myapi.com/v1/login");
HttpRequest httpRequest = new HttpRequest();
Task<LoginResponse> loginTask = httpRequest.Authentication(request,uri);
returnValue = loginTask.GetAwaiter().GetResult();
return returnValue;
}
现在这是我在 HttpRequest 中调用身份验证方法时遇到的两个问题:
public async Task<LoginResponse> Authentication(LoginRequest request,Uri url)
{
var dict = new Dictionary<string,string>();
dict.Add("login",request.login);
dict.Add("password",request.Password);
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json")
);
var req = new HttpRequestMessage(HttpMethod.Post,url) {
Content = new FormUrlEncodedContent(dict)
};
var response = await client.SendAsync(req);
string output = await response.Content.ReadAsstringAsync();
Console.WriteLine(JsonConvert.DeserializeObject(output));
LoginResponse returnValue = JsonConvert.DeserializeObject<LoginResponse>(output);
return returnValue;
}
Key: "username"
value: "helloWorld"
Key: "username"
value: "helloWorld"
我也尝试使用字典来做这样的事情:
var dictionary = ToDictionary<string>(request);
foreach(keyvaluePair<string,string> entry in dictionary)
{
dictionary.Add(entry.Key,entry.Value);
Console.WriteLine(entry.Key);
Console.WriteLine(entry.Value);
}
ToDictionnary 如下:
public Dictionary<string,TValue> ToDictionary<TValue>(object obj)
{
var json = JsonConvert.SerializeObject(obj);
var dictionary = JsonConvert.DeserializeObject<Dictionary<string,TValue>>(json);
if (dictionary != null)
{
return dictionary;
}
// handle exception here...
return null;
}
它也复制了键值并抛出了异常。
我的第二个问题是我不知道如何将 JsonPropertyName 与属性名称映射。 我的调用返回一个字符串,我将其转换为对象。
我的模型如下:
public class LoginResponse
{
[JsonPropertyName("access_token")]
public string Accesstoken { get; set; }
[JsonPropertyName("type_token")]
public string TokenType { get; set; }
public LoginResponse() { }
}
因此,我确实得到了一个字符串,我将其映射为对象,但未映射键: 我得到:
{ "access_token": "abcdef","type_token": "Bearer" }
虽然我期待:
{ "Accesstoken": "abcdef","TokenType": "Bearer" }
解决方法
我用序列化解决了我的问题。我正在使用 System.Text.Json.Serialization ... 我在模型中使用 Newtonsoft.Json 代替。
我也更改了注释:
[JsonPropertyName("access_token")]
与:
[JsonProperty(PropertyName = "access_token")]