简体   繁体   中英

Can a C# console app call a WEB API using classes from .Net 3.5?

How can I re-write the console app below using classes from .NET 3.5? What classes should I be looking into? The console application needs to be compiled with .net 3.5 and cannot use the HttpClient class. And it needs to be calling an WEB API and pass an XML string as I am doing below:

string xml = "<test>blah</test>";
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://CONTOSO/");
HttpContent xmlContent = new StringContent(xml);

HttpResponseMessage response = client.PostAsync("API/Import/", xmlContent).Result;
if (response.IsSuccessStatusCode)
{
    Console.WriteLine(String.Format("Success."));
}
else
{
    Console.WriteLine("{0: } {1}", (int)response.StatusCode, response.ReasonPhrase);
}

I tried the code below but I get error: "ERROR: (500) Internal Server Error.":

string baseAddress = "http://CONTOSO/";
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(baseAddress + "API/Import");
req.Method = "POST";
req.ContentType = "text/xml";
Stream reqStream = req.GetRequestStream();
string fileContents = xml;
byte[] fileToSend = Encoding.UTF8.GetBytes(fileContents);
reqStream.Write(fileToSend, 0, fileToSend.Length);
reqStream.Close();
HttpWebResponse resp = (HttpWebResponse)req.GetResponse(); //<== "ERROR: (500) Internal Server Error."
Console.WriteLine("HTTP/{0} {1} {2}", resp.ProtocolVersion, (int)resp.StatusCode, resp.StatusDescription);

RestSharp does support .NET 3.5,

https://github.com/restsharp/RestSharp

Thus, you might use this open source HTTP client library to consume Web API.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM