I have create a method in the service class that makes a call to another class to invoke the instance of webclient object. I am trying to perform Post operation using UploadString. However, when the method is called, I'm getting null reference exception. The webclient does not seems to be executing. Here's my code structure:
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;
}
}
The xml payload will just contain some xmlstring with values that the api will read it by itself.