question

CalebRinderer-9481 avatar image
0 Votes"
CalebRinderer-9481 asked DuaneArnold-0443 commented

Having Issues Making HTTP Post Request in C#

I have written some code in C# that compiles and runs perfectly on its own, but when I try to put it into a Visual Studio windows form application, I keep running into errors. The code in question sends a POST request to a local device and then downloads the response as a CSV. I can run this without any errors typically. But when I run it through the Visual Studio program I get the following error:
The underlying connection was closed unexpectedly.

I am making both requests on the same device to the same "server" so there has to be something with the .NET framework that's tripping me up I am guessing. Here is the code:

             var url = "http://local.ip.address/";
             using (var wb = new WebClient())
             {
                 var data = new NameValueCollection();
                 data["data_val1"] = "data";
                 data["data_val2"] = "data";
                 data["data_val3"] = "data";
                 data["data_val4"] = "data";
                 data["data_val5"] = "data";
                 var response = wb.UploadValues(url, "POST", data);
                 string responseInString = Encoding.UTF8.GetString(response);
                 string path = @"C:\LOCALPATH\httpResponse.csv";
                 if (!File.Exists(path))
                 {
                     // Create a file to write to.
                     using (StreamWriter sw = File.CreateText(path))
                     {
                         sw.WriteLine(responseInString);
                     }
                 }
             }

Any help is appreciated! Thanks!

dotnet-csharp
· 3
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.


In which circumstances (what kind of project and framework) does it work?

0 Votes 0 ·

I can compile and run it fine in VS Code using dotnet build and dotnet run. In this case does that mean it's also using .NET? I am unfamiliar with C# so that's also leading to some confusion.

0 Votes 0 ·

You need to put a try/catch and see if you get an inner.exception.message that may reveal the underlying cause.

https://www.c-sharpcorner.com/uploadfile/puranindia/innerexception-in-C-Sharp/

0 Votes 0 ·

0 Answers