Search code examples
c#xamarin.formsportable-class-library

Xamarin.Forms Can't Get WCf Result Method by Url


I create a wcf using the following code :

[ServiceContract]
   public interface IRestServiceImpl
    {           
    [OperationContract]
    [WebGet( ResponseFormat = WebMessageFormat.Json,
        BodyStyle =WebMessageBodyStyle.Wrapped,
        UriTemplate = "json")]
    string JSONData();
}



    public class RestServiceImpl : IRestServiceImpl
        {
            public string JSONData()
            {
                return "You Requested Prodcut";
            }
        }

and I added WCF to local IIS and it is working fine as the following: enter image description here

when I am trying to get value from xamarin.forms app I get an exception

System.Net.WebExceptionStatus.ConnectFailure

, what the result should be ?

 private async Task DownloadInfo()
        {
            var Uri = "http://localhost:8020/wcfrest/RestServiceImpl.svc/json";
            var httpClient = new HttpClient();
            var json= await  httpClient.GetStringAsync(Uri);//I get exception here System.Net.WebExceptionStatus.ConnectFailure
        } 

Solution

  • It can be caused by quite a few things:

    1. Did you add Internet permission to your app?

    2. Are you sure that your device is in the same network as your API?

    3. Try to use an IP address instead of localhost

    4. Add host to your HttpClient object:

      var httpClient = new HttpClient { Host = "localhost" };