'Xamarin forms app Connection to Asp.net core web Api

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://docs.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.



Solution 1:[1]

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

Solution 2:[2]

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://docs.microsoft.com/en-us/xamarin/cross-platform/deploy-test/connect-to-local-web-services

Solution 3:[3]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Abanoub Refaat
Solution 2 Nicolas Quintana
Solution 3 Rajarajan