My web api needs to return a response. Can't seem to get it right. Here is the code for the controller.
//Controller Code
// POST api/<controller>
[HttpPost]
//public IActionResult Post([FromBody] customersT customers)
public string Post([FromBody] customersT customers)
{
SageHelper sageHelper;
if(!ModelState.IsValid)
{
return "Invalid XML"; //BadRequest(ModelState);
}
else
{
sageHelper = new SageHelper(customers);
}
return sageHelper.ReturnValue; //Ok();
}
Here is the helper class that will do the post to Sage
public static async Task CreateCustomer(string uri, customersT customers)
{
var customer = new
{
CustomerNumber = customers.Items[0].custNo,
ShortName = customers.Items[0].custNo,
CustomerName = customers.Items[0].custAddresses[0].name,
GroupCode = "RTL"
};
await SendRequest(new HttpMethod("POST"), uri + @"AR/ARCustomers", customer);
}
public static async Task<object> SendRequest(HttpMethod method, string requestUri, object payload = null)
{
HttpContent content = null;
string responsePayload = "";
// Serialize the payload if one is present
if (payload != null)
{
var payloadString = JsonConvert.SerializeObject(payload);
content = new StringContent(payloadString, Encoding.UTF8, "application/json");
}
// Create the Web API client with the appropriate authentication
using (var httpClientHandler = new HttpClientHandler { Credentials = new NetworkCredential("USER", "PASSWORD") })
using (var httpClient = new HttpClient(httpClientHandler))
{
// Create the Web API request
var request = new HttpRequestMessage(method, requestUri)
{
Content = content
};
// Send the Web API request
try
{
var response = await httpClient.SendAsync(request);
responsePayload = await response.Content.ReadAsStringAsync();
var statusNumber = (int)response.StatusCode;
response.StatusCode);
if (statusNumber < 200 || statusNumber >= 300)
{
// Console.WriteLine(responsePayload);
throw new ApplicationException(statusNumber.ToString());
}
}
catch (Exception e)
{
Environment.Exit(0);
}
}
return string.IsNullOrWhiteSpace(responsePayload) ? null : JsonConvert.DeserializeObject(responsePayload);
}
When the HTTP post hits the controller, it sends the request off to the SageHelper object which processes the data and pushes into Sage. The SendRequest method returns a string which I actually don't want for this project. Where it gets the response.statusCode from the response object, I am trying to get that set into a public property of the SageHelper class
public string ResponseCode { get; set; }Normally, I would just put ResponseCode = response.statusCode; in the SendRequest method but I can't see the property from that method.