Ame
Ame

Reputation: 35

WebClient UploadString returns html code and does not send data

I'm trying to send some string from a service to a webmethod service with the following code:

private void SendRequest(string filePath, string webService)
{ 
    try
    {
         using (var wb = new WebClient())
         {
             string data = File.ReadAllText(filePath);
             data = "data=" + data;
             string res = wb.UploadString(webService, data);                 
         }
    }
    catch (Exception e)
    {
        logEvents.Write(MyLogClass.LogLevel.Info, "Data not sent " + e.Message);
    }
}        

For some reason I don't know res is returning the html code of the frontpage.

I was doing this previously with node and my webservice would accept the string without a problem and return 200.

The code of the web service starts as follows:

[WebMethod]
public static string Data(string data)

I've tried formatting the data in several ways and changing the arguments and the URLs are well. The problem is not in the web service since it works fine with my node request. What could it be?

Upvotes: 0

Views: 1148

Answers (2)

Ame
Ame

Reputation: 35

Solved this by serializing the data being sent and using WebRequest instead of WebClient.

Edit

var webRequest = WebRequest.Create(webService);
                webRequest.Method = "POST";
                webRequest.ContentType = "application/json";
                string data = File.ReadAllText(filePath);
                var jsonObject = new { data };
                var serializedObject = JsonConvert.SerializeObject(jsonObject);
                var bytes = Encoding.ASCII.GetBytes(serializedObject);
                var requestStream = webRequest.GetRequestStream();
                requestStream.Write(bytes, 0, bytes.Length);
                HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();

Upvotes: 1

Pankaj
Pankaj

Reputation: 568

Try specifying Headers explicitly.

using (var wb = new WebClient())
{
    wb.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
    string data = File.ReadAllText(filePath);
    data = "data=" + data;
    string res = wb.UploadString(webService, /*"POST",*/ data);
}

Upvotes: 0

Related Questions