The remote server returned an error: (400) Bad Request while consuming a WCF Service

Please view the code given below. While the debug reaches the request.GetResponse() statement the error has been thrown.

Uri uri = new Uri(address);
string data = "<s:Envelope xmlns:s='http://schemas.xmlsoap.org/soap/envelope/'><s:Body><HasRole xmlns='http://tempuri.org/'><userName>" + sid + "</userName><role>" + role + "</role></HasRole></s:Body></s:Envelope>";

data.Replace("'", "\"");

// Create a byte array of the data we want to send  
byte[] byteData = UTF8Encoding.UTF8.GetBytes(data);

if (uri.Scheme == Uri.UriSchemeHttps)
{
    HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);
    request.Method = "POST";// WebRequestMethods.Http.Post;
    request.ContentLength = byteData.Length;
    request.ContentType = "application/soap+xml; charset=UTF-8"; // "text/xml; charset=utf-8";
    //request.ContentType = "application/x-www-form-urlencoded";

    //Stream requestStream = request.GetRequestStream();
    using (Stream writer = request.GetRequestStream())
    {
        writer.Write(byteData, 0, byteData.Length);
    }
    //writer.Close();

    using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
    {
        // Get the response stream  
        StreamReader reader = new StreamReader(response.GetResponseStream());
        string tmp = reader.ReadToEnd();
        Response.Close();
        Response.Write(tmp);
    }

Upvotes: 2

Views: 7872

Answers (2)

Vadim
Vadim

Reputation: 17957

As has been mentioned you should use the 'Add Service Reference' to access the WCF service from a .NET client. However, if you're emulating trying to connect from a non .NET client, your soap envelope is missing the header information.

<s:Header>
   <Action s:mustUnderstand="1" xmlns="http://schemas.microsoft.com/ws/2005/05/addressing/none">
specify your action namespace here (e.g. http://tempuri.org/ISomeService/Execute)
   </Action>
</s:Header>

Upvotes: 1

Hardip Singh
Hardip Singh

Reputation: 136

I would double check the URL. If the URL looks ok on the client side, I recommend looking at access logs on your server to see what URL is being hit. 4xx errors mean a resource was not found. If the endpoint was correct, but the request was fubared, you would get a 5xx error code. (Assuming that your server side frameworks uses standard HTTP Response Codes).

Upvotes: 1

Related Questions