I have the following function Handle_Log_Clicked()
which calls async Task CreateLogCall which makes an HTTP POST request using the repository.CREATE()
method and returns HttpResponseMessage type as return value :
I have to use the response in Handle_Log_Clicked()
method to retrieve Headers from the HttpResponseMessage response that I get from CreateLogCall ()
.
In the below code the response does not get set in HttpResponseMessage response
.
When I am trying to take a substring of the response resulting in an error.
async void Handle_Log_Clicked(object sender, System.EventArgs e)
{
try
{
HttpResponseMessage response = await CreateLogCall();
Debug.WriteLine("Response: ", response);
var resultHeader = response.Headers.Location.ToString();
string relatedCallID = resultHeader.Substring(resultHeader.IndexOf('('), resultHeader.Length -1 );
await CreateLogCallProducts(relatedCallID);
if (!response.IsSuccessStatusCode)
await DisplayAlert("Failure", "The data could not be saved", "Ok");
else
await DisplayAlert("Success", "The call is logged successfully", "Ok");
}
catch (Exception err)
{
await DisplayAlert("Error", "Please fill all the details", "Ok");
Debug.WriteLine(err.Message);
}
}
public async Task<HttpResponseMessage> CreateLogCall()
{
HttpResponseMessage result = null;
try
{
if (isPrescriber)
{
Debug.WriteLine("inside prescriber calls");
result = await repository.Create(GlobalVariables.AuthToken, "xxxx", logCall);
}
else
{
result = await repository.Create(GlobalVariables.AuthToken, "yyyyy", logCall);
}
return result;
}
catch (Exception e)
{
Debug.WriteLine(e.Message);
}
return result;
}
Inside repository.cs
public async Task<HttpResponseMessage> Create(string accessToken, string entity, JObject data)
{
// The URL for the OData organization web service.
string url = GlobalVariables.RootUrl + GlobalVariables.EndPoint + entity;
var content = new StringContent(data.ToString(), Encoding.UTF8, "application/json");
// Build and send the HTTP request.
HttpClient httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
// Wait for the web service response.
HttpResponseMessage response;
response = await httpClient.PostAsync(url, content);
Debug.WriteLine(response);
return response;
}
While putting the debugger I can see the response value being pass to Handle_Log_Clicked() but when the code reaches the substring method it throws error :
Index and length must refer to a location within the string. Parameter name: length
Also the code : Debug.WriteLine("Response: ", response);
does not print the response but debugger shows value in it.