I have a method in C# which communicates with REST API.It has a several small task like splitting of a string ,checking a commandText is valid or not,POST and GET JSON payload to/from REST API.
public string PostToAPI([FromBody]string value)
{
string input = value;
//splitting of string into substrings
var str = input.Split(new[] { ' ' }, 2);
var payload = new testModel
{
Command = str[0],
CommandText = str[1]
};
//list of commands
List<string> cmdText = new List<string>(){"/calc", "/test" };
//check CommandText is valid or not
if(cmdText.Contains(payload.CommandText))
{
//return valid
}
// Serialize our concrete class into a JSON String
var stringPayload = JsonConvert.SerializeObject(payload);
try
{
// Wrap our JSON inside a StringContent which then can be used by the HttpClient class
var httpContent = new StringContent(stringPayload, Encoding.UTF8, "application/json");
using (var httpClient = new HttpClient())
{
HttpResponseMessage message = httpClient.PostAsync("https://testapi.com", httpContent).Result;
if (message.IsSuccessStatusCode)
{
string result = message.Content.ReadAsStringAsync().Result;
return result;
}
else
return message.StatusCode+"kindly contact to administrator";
}
}
catch (Exception ex)
{
return ex.InnerException.ToString();
}
}
splitting of a string splits the string into two substrings.
checking a commandtext, checks commandtext is valid or not.
they all are in one method.From architecture/design point of view is this right or should i split the task into different module or in different classes to add more flexibility, readability,As there may be a situation where i just need to add commands string and don't want to touch the other task.
How to organize such c# tasks into different modules/class to make them more flexible, readable? Thanks!