我有以下函数Handle_Log_Clicked()
调用异步任务CreateLogCall,它使用repository.CREATE()
方法发出HTTP POST请求,并返回HttpResponseMessage类型作为返回值:
我必须使用Handle_Log_Clicked()
方法中的响应从我从CreateLogCall ()
获得的HttpResponseMessage响应中检索Headers。
在下面的代码中,响应未在HttpResponseMessage response
中设置。
当我试图获取响应的子字符串时会导致错误。
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;
}
放入调试器时,我可以看到响应值传递给Handle_Log_Clicked(),但是当代码到达substring方法时,它会抛出错误:
索引和长度必须指向字符串中的位置。 参数名称:长度
代码:Debug.WriteLine("Response: ", response);
不会打印响应,但调试器会在其中显示值。