6

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?

3
  • check out restsharp.org Commented Dec 22, 2014 at 12:14
  • 2
    You can use WebRequest, msdn.microsoft.com/en-us/library/… Commented 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 RestSharp Commented Dec 23, 2014 at 10:58

2 Answers 2

6

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;
Sign up to request clarification or add additional context in comments.

5 Comments

you shouldn't use Result to read values from Task! you should await them!
@pikax: Thanks for the tip. Any reason why we should not use Result() to read the value?
@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 programs
@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.
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.
4

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
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.