0

I have a xamarin forms app that uses a (local) web api (using asp.net core) to connect to Sql Server Database. i tried the demo provided here https://learn.microsoft.com/en-us/aspnet/web-api/overview/advanced/calling-a-web-api-from-a-net-client to make a client api calls but it uses a console app instead of mobile app and it worked fine.

using both Microsoft.AspNet.WebApi.Client and Newtonsoft.Json Nuget Packages

Xamarin forms client code

 client.BaseAddress = new Uri("http://myIP:port/");

            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(
                new MediaTypeWithQualityHeaderValue("application/json"));
            try
            {
                HttpResponseMessage response = await client.PostAsJsonAsync("api/users", user);
                response.EnsureSuccessStatusCode();
                return response.IsSuccessStatusCode;
            }
            catch (Exception ex)
            {

                Debug.WriteLine("Post Api Exception Msg: " + ex.Message, Class_Name);
                return false;
            }

and my web-Api code

public IActionResult Post([FromBody] User user)
        {
        if(!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }
    
    bool result= repository.Create(user);
    if(result)
    {
        return Ok();
    }
    else
    {
        return StatusCode(500);
    }
}

and i have tested the api code and it's working fine. but whenever i try to make calls from my xamarin app

first) i placed a breake point in the web-api code it never gets hit

second) i keep getting the exception

[monodroid-net]   --- End of managed Java.Net.SocketException stack trace ---
[monodroid-net] java.net.SocketException: Socket closed
[monodroid-net]     at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:394)
[monodroid-net]     at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:230)
[monodroid-net]     at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:212)
[monodroid-net]     at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:436)
[monodroid-net]     at java.net.Socket.connect(Socket.java:621)
[monodroid-net]     at com.android.okhttp.internal.Platform.connectSocket(Platform.java:145)
[monodroid-net]     at com.android.okhttp.internal.io.RealConnection.connectSocket(RealConnection.java:141)
[monodroid-net]     at com.android.okhttp.internal.io.RealConnection.connect(RealConnection.java:112)
[monodroid-net]     at com.android.okhttp.internal.http.StreamAllocation.findConnection(StreamAllocation.java:184)
[monodroid-net]     at com.android.okhttp.internal.http.StreamAllocation.findHealthyConnection(StreamAllocation.java:126)
[monodroid-net]     at com.android.okhttp.internal.http.StreamAllocation.newStream(StreamAllocation.java:95)
[monodroid-net]     at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:281)
[monodroid-net]     at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:224)
[monodroid-net]     at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:461)
[monodroid-net]     at com.android.okhttp.internal.huc.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:127)

I think it means that there is a problem with the connection socket but I have no idea what the problem is and how to resolve it.

3
  • 1
    use the device/emulator browser to verify connectivity to your webserver. If you are using the VS web server it typically does not allow requests from remote hosts by default Commented Mar 16, 2022 at 15:43
  • @Jason i ran the web-api project and tested the crud operations using PostMan tool. and for the second part of your reply how come the web-api doesn't support the remote access and what the solution to that. Commented Mar 16, 2022 at 17:19
  • You need to test connectivity between your device/emulator and your server. Using Postman doesn't do that. There are thousands of existing posts about how to enable the VS server for remote requests. Commented Mar 16, 2022 at 17:57

3 Answers 3

1

You need change this:

client.BaseAddress = new Uri("http://10.0.2.2:port/");

instead of:

client.BaseAddress = new Uri("http://myIP:port/");

for more information, see the official documentation: https://learn.microsoft.com/en-us/xamarin/cross-platform/deploy-test/connect-to-local-web-services

Sign up to request clarification or add additional context in comments.

2 Comments

thanks for the fast answer but, it didn't solve my problem. i've changed the base address code to private string BaseAddress = DeviceInfo.Platform == DevicePlatform.Android ? "10.0.2.2:port" : "localhost:port"; and i still get the same Exception + those additional info Exception: the operation was canceled. [DpmTcmClient] Couldn't find 'tcm' socket after 120times. quit trying
Note that am testing on real android device.
0

In order to access your location machine's web API in the android emulator, you must use the IP 10.0.2.2, see the link below for assistance

https://developer.android.com/studio/run/emulator-networking#networkaddresses

2 Comments

thanks for the fast answer but, it didn't solve my problem. i've changed the base address code to private string BaseAddress = DeviceInfo.Platform == DevicePlatform.Android ? "10.0.2.2:port" : "localhost:port"; and i still get the same Exception + those additional info Exception: the operation was canceled. [DpmTcmClient] Couldn't find 'tcm' socket after 120times. quit trying
Note that am testing on real android device.
0

I finally solved the problem by using the Conveyor Extension here is the steps:

  1. open visual studio and select from the tool bar extensions -> manage extension.enter image description here

  2. in online section search for Conveyor By Keyoti. enter image description here

  3. after installing the extension restart your Visual studio and it will resume installing.

after that you need to Add a firewall rule for your api to use.

  1. open the windows defender firewall with advanced security form the start menu or type in the search box wf.mfc whatever works for you. enter image description here

for full steps watch this brief tutorial. Conveyor: Remote access to IIS Express web application [Updated]

after making all firewall configuration except the part of access over the internet (because in my case both my api and my android device are connected on the same network )

i did not work so i tried this: 5) click on tools -> conveyor allow remote access it will open up this window click on options. enter image description here

on the far right side there option I clicked on FireWall check to check any issue with the firewall enter image description here

afterwards it will open a window display the issues with the firewall and you'll have two option to apply firewall rules automatically or to apply firewall rules manually

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.