1
votes

I am doing some testing for a Xamarin Android app with a simple local WCF service to prove my connection code works.

Service: [OperationContract] string Ping(); … public string Ping() { return "Pong"; }

Test Code in Xamarin App:

var request = HttpWebRequest.Create(string.Format(@"http://192.168.1.175/_Services/TestService1.svc/Ping"));

request.Credentials = CredentialCache.DefaultCredentials;
request.ContentType = "application/x-www-form-urlencoded;charset=UTF-8";
request.ContentLength = 0; //pass.Length;
request.Method = "POST";

using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)  //Errors out here
{
  using (StreamReader reader = new StreamReader(response.GetResponseStream()))
  {
    var content = reader.ReadToEnd();
    Console.Out.WriteLine("Response Body: \r\n {0}", content);
  }
}

Error:

The remote server returned an error: (400) Bad Request.

Edit:

When using ServiceReference, the following works:

private void button3_Click(object sender, EventArgs e) { ServiceReference1.TestService1Client client = new ServiceReference1.TestService1Client();

        string returnString;

        returnString = client.Ping();
        label1.Text = returnString;
    }

Slightly different code still does not work: private void button4_Click(object sender, EventArgs e) { //string serviceUrl = "http://192.168.1.175/_Services/TestService1.svc"; string serviceUrl = "http://localhost/_Services/TestService1.svc";

        HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(new Uri(serviceUrl + "/Ping"));
        httpRequest.Accept = "text/xml";
        httpRequest.ContentType = "text/xml";
        httpRequest.Method = "POST";
        httpRequest.ContentLength = 0;
        httpRequest.KeepAlive = false;

        using (HttpWebResponse httpResponse = (HttpWebResponse)httpRequest.GetResponse()) //400 Bad Request
        {
            using (Stream stream = httpResponse.GetResponseStream())
            {
                label1.Text = (new StreamReader(stream)).ReadToEnd();
            }
        }
    }
1
It's not clear what you are asking here? What have you tried so far? Can other client connect? If possible, please provide a Short, Self Contained, Correct (Compilable), Example.Rangi Keen
@Rangi Keen Trying to figure out "The remote server returned an error: (400) Bad Request." on line of code marked.TheJoe
My WCF service does work from desktop forms app using Service Reference. No luck in Xamarin app so far.TheJoe

1 Answers

0
votes

The answer was rooted in System.ServiceModel.Activation.WebServiceHostFactory

For some reason none of my sources mentioned this during research for using HttpWebRequest.

I found the reference by chance when looking at Android WCF consuming. https://minafayek.wordpress.com/2013/04/02/consuming-iis-published-restful-wcf-service-from-android-over-wifi/

I got my testing programs working so, I should be able to move forward.