I have developed a Web API, I can access my api by using HttpClient in .NET 4 and 4.5 but I want to access this api from an existing .NET 3.5 application. Is it possible? I have learned from internet that HttpClient is not supported in .net 3.5, so how I consume this service in .net 3.5 application?
-
check out restsharp.orgwal– wal2014-12-22 12:14:12 +00:00Commented Dec 22, 2014 at 12:14
-
2You can use WebRequest, msdn.microsoft.com/en-us/library/…Coding Flow– Coding Flow2014-12-22 12:14:30 +00:00Commented Dec 22, 2014 at 12:14
-
WebAPI is the same as any other REST API. You can use whatever method you want to send an HTTP request, eg the built-in WebRequest class, any other library like RestSharpPanagiotis Kanavos– Panagiotis Kanavos2014-12-23 10:58:48 +00:00Commented Dec 23, 2014 at 10:58
Add a comment
|
2 Answers
Checkout this link for .net version 3.5:
OR TRY THIS FOR 3.5
System.Net.WebClient client = new System.Net.WebClient();
client.Headers[HttpRequestHeader.ContentType] = "application/json";
client.BaseAddress = "ENDPOINT URL";
string response = client.DownloadString(string.Format("{0}?{1}", Url, parameters.UrlEncode()));
This is how I am making call in .net 4.5.
var url = "YOUR_URL";
var client = new HttpClient();
var task = client.GetAsync(url);
return task.Result.Content.ReadAsStringAsync().Result;
5 Comments
pikax
you shouldn't use Result to read values from Task! you should await them!
SharpCoder
@pikax: Thanks for the tip. Any reason why we should not use
Result() to read the value?Panagiotis Kanavos
@SharpCoder that's what
await is for. By calling Result you are blocking the calling thread, losing any asynchronous benefit. If you can't use await you can use ContinueWith to keep working asynchronously. The only place where this is necessary though is in the Main method of Console programsSharpCoder
@PanagiotisKanavos: Thanks for the explination. I will test my code. Currently I am using Result() & it seems to be working asynchronously. But I need to check.
Panagiotis Kanavos
It doesn't. Result blocks until the task finishes. There's no ambiguity here. You may receive a response from your local machine so fast you don't notice the delay, or you may be running the code block inside another Task.
You could use WebRequest
// Create a request for the URL.
var request = WebRequest.Create ("http://www.contoso.com/default.html");
request.ContentType = contentType; //your contentType, Json, text,etc. -- or comment, for text
request.Method = method; //method, GET, POST, etc -- or comment for GET
using(WebResponse resp = request.GetResponse())
{
if(resp == null)
new Exception("Response is null");
return resp.GetResponseStream();//Get stream
}