I have a web service in web api project in a separate solution. I am trying to access that web service from a Xamarin project. I am using my Android phone to debug but I get this error. All of the articles I came across to access web services, use an emulator. Is it because of this that I'm getting this error or have I missed anything?
Update 1:
My code is as follows and the error occurs at line 10 (line containing using (WebResponse response = await request.GetResponseAsync())
).
private async Task<JsonValue> GetNamesAsync()
{
try
{
string url = "http://{network-ip-address}:{port}/api/Names";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(new Uri(url));
request.ContentType = "application/json";
request.Method = "GET";
using (WebResponse response = await request.GetResponseAsync())
{
//Some code here
}
return null;
}
catch(Exception ex)
{
return null;
}
}
Update 2:
If I Step Into
(F11), then after about 2 clicks, the following Dialog Box opens.
You are trying to step into the code:
WebResponse response = await request.GetResponseAsync()
That is, you are trying to debug the GetResponseAsync()
method in the HttpWebRequest
class. The source code for this class has not been loaded into your project (only the compiled .dll
) and so you cannot step into this line.
Try F10
to step over this line.
You may now get the same error - however, this time the reason will be different. As the GetResponseAsync()
method has been awaited, the programme flow goes back to the method that called GetNamesAsync()
. If that call was awaited, and the chain of calls to that method where all awaited back to the Activity
method (as should be so to not block the UI), the next line of code to execute will be a line of code somewhere in the Xamarin/Android source code that again you don't have access to.
e.g.
1 class MyActivity : Activity
2 {
3 // This function is called by the Xamarin/Android systems and is not awaited.
4 // As it is marked as async, any awaited calls within will pause this function,
5 // and the application will continue with the function that called this function,
6 // returning to this function when the awaited call finishes.
7 // This means the UI is not blocked and is responsive to the user.
8 public async void OnCreate()
9 {
10 base.OnCreate();
11 await initialiseAsync(); // awaited - so will return to calling function
12 // while waiting for operation to complete.
13
14 // Code here will run after initialiseAsync() has finished.
15 }
16 public async Task initialiseAsync()
17 {
18 JsonValue names = await GetNamesAsync(); // awaited - so will return to Line 11
19 // while waiting for operation to complete.
20
21 // Code here will run after GetNamesAsync() has finished.
22 }
23 }