Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Downgrade code of HttpClient .NET 4.5 to .NET 4.0

I have this code that is working fine in .NET 4.5.

var handler = new HttpClientHandler();
handler.UseDefaultCredentials = true;
handler.PreAuthenticate = true;
handler.ClientCertificateOptions = ClientCertificateOption.Automatic;

var client = new HttpClient(handler);
client.BaseAddress = new Uri("http://localhost:22678/");
client.DefaultRequestHeaders.Accept.Add(
                    new MediaTypeWithQualityHeaderValue("application/json"));

var loginBindingModel = new LoginBindingModel { Password = "test01", UserName = "test01" };

var response = await client.PostAsJsonAsync("api/Account/Login", loginBindingModel);
                response.EnsureSuccessStatusCode(); // Throw on error code.
                tokenModel = await response.Content.ReadAsAsync<TokenModel>();

Now I have to do the same thing in .NET 4.0.

But I am facing two problems I do not know how to resolve them.

  1. In .NET 4.0. method client.PostAsJsonAsync does not exist.
  2. The existing method is client.PostAsync and it needs HttpContext.

enter image description here

I do request within WPF client... Guys, I have no clue what I can do to archive the same functionality...

Please, help!

like image 556
Friend Avatar asked Jan 21 '14 19:01

Friend


People also ask

How to downgrade NET Framework in Visual Studio?

Downgrade .net framework in application from visual studio 2. Install .net framework 4.8 on the server or downgrade to lower version so that server has that version already installed. Upgrading .net framework sometimes create some issues like some .net framework application which is already in the server might not work correctly. 1 .

What version of the NET Framework is required for retargeting?

If looser .NET Framework 4.0 validation is needed, the validating application can target version 4.0 of the .NET Framework. When retargeting to .NET Framework 4.5, however, code review should be done to be sure that invalid URIs (with spaces) are not expected as attribute values with the anyURI data type.

What version of the NET Framework do I need to validate?

The change affects only applications that target the .NET Framework 4.5. If looser .NET Framework 4.0 validation is needed, the validating application can target version 4.0 of the .NET Framework.

What happens when you downgrade a framework?

While downgrading the .net framework for the project, some errors may occur at a compiled time and can't reference the namespace. So, some packages and libraries may not work if you downgrade so read the documentation properly and if all of your packages support on lower .net version then Ok and move forward for the process.


3 Answers

Suggest using the BCL / async / "Microsoft HTTP Client Libraries" helper projects to "supplement" .Net 4.0 with equivalent functionality to .Net 4.5 (Can find the latest versions in the NuGet package manager.) See the following link for more info: http://www.nuget.org/packages/microsoft.bcl.async (Note: you can get support for http client via same basic mechanism)

like image 93
Wonderbird Avatar answered Oct 01 '22 13:10

Wonderbird


Just for someone who is looking for the same .NET 4.0 pure solution I found that code working fine. But It does not have ASYNC/AWAIT thing that should be implemented as well. Anyway it is working exactly the same way as my code in the question.

var webAddr = "http://localhost:22678/api/Account/Login";
var httpWebRequest = (HttpWebRequest)WebRequest.Create(webAddr);
httpWebRequest.ContentType = "application/json; charset=utf-8";
httpWebRequest.Method = "POST";

using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
      var loginBindingModel = new WebAPILoginBindingModel { Password = "test01", UserName = "test01" };
      var myJsonString = Newtonsoft.Json.JsonConvert.SerializeObject(loginBindingModel);
                    streamWriter.Write(myJsonString);
                    streamWriter.Flush();
}

var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
    var result = streamReader.ReadToEnd();
}

If you want to use use ASYNC/AWAIT for .NET 4.0 you have to install Microsoft.BCL dll and use async versions of HttpClient as well.

like image 41
Friend Avatar answered Oct 01 '22 14:10

Friend


Even after installing the following packages i got other errors.

Install-Package Microsoft.Net.Http

Install-Package System.Net.Http.Formatting.Extension

Turns out Install-Package System.Net.Http.Formatting.Extension installs version of system.net that does not support dot net 4. So I has to stick to PostAsync and create an httpContent object from my custom object.

So

PostAsJsonAsync("api/Account/Login", loginBindingModel)

Becomes (Note i used json.net here )

public  HttpContent CreateHttpContent(object data)
        {  
            return new StringContent(JsonConvert.SerializeObject(data), Encoding.UTF8, "application/json");
        }

PostAsync("api/Account/Login",CreateHttpContent(loginBindingModel))

like image 39
flexxxit Avatar answered Oct 01 '22 14:10

flexxxit