【发布时间】:2021-05-20 23:15:07
【问题描述】:
我在服务类中创建了一个方法,该方法调用另一个类来调用 webclient 对象的实例。我正在尝试使用 UploadString 执行 Post 操作。但是,当调用该方法时,我得到空引用异常。网络客户端似乎没有执行。这是我的代码结构:
Service.cs
public static class Service
{
private static readonly WebClientService _webClientService;
private static async Task<string> ChangePassword(string ip, string pass)
{
_webClientService.UpdatePassword(serverIp, pass);
}
}
WebClientService.cs
public class WebClientService
{
private static readonly WebClient _client = new();
private static string _getNewPwdUrl =
"https://execute-api.com/default/pwd?={0}/user/{1}";
private static string _postNewPwdUrl =
"http://{0}/bin/link?cmd=chngpwd&oldpwd={1}";
static WebClientService()
{
_client.UseDefaultCredentials = true;
}
public string UpdatePassword(string serverIp, string pass)
{
string result = string.Empty;
string urlPwd = string.Format(_getNewPwdUrl, "admin", pass);
string xmlPayload = DownloadXml(urlPwd);
string updateUrl = string.Format(_postNewPwdUrl, serverIp, pass);
try
{
result = _client.UploadString(updateUrl, xmlPayload);
}
catch (Exception ex)
{
Ilogger.Error($"UpdatePassword > Error: {ex.Message},
stackTrace: {ex.StackTrace}");
}
return result;
}
public string DownloadXml(string address)
{
string result = string.Empty;
try
{
result = _client.DownloadString(address);
}
catch (Exception ex)
{
Ilogger.Error($"DownloadXml > Error: {ex.Message},
stackTrace: {ex.StackTrace}");
}
return result;
}
}
xml 有效负载将只包含一些带有值的 xmlstring,api 将自行读取它。
【问题讨论】:
-
哪一行出现错误,
result = _client.UploadString(updateUrl, xmlPayload);? -
不,在我调用 UpdatePassword 时在 service.cs 本身中。通过设置断点,我意识到它停在那里。那就是我将 ObjectReference 设置为对象实例的地方。
-
我认为我创建webclient实例的格式不正确。