Windows.Web.Http.HttpClient missing GetAwaiter - c#

I have this error in visual studio. It is PCL I have added my solution and I am trying to use Windows.Web.Http.HttpClient and not the one in System.net.http. I have a reference for "Windows" but gets the following error by the GetAsync call:
'IAsyncOperationWithProgress' does not contain a definition for 'GetAwaiter' and no extension method 'GetAwaiter' accepting a first argument of type 'IAsyncOperationWithProgress' could be found (are you missing a using directive for 'System'?)
"using System;" is in the top of the file. In many examples like the following I can see it should work but I must be missing something: https://learn.microsoft.com/en-us/uwp/api/windows.web.http.httpclient
using (HttpClient client = new HttpClient())
{
var response = await client.GetAsync(GetBaseUri());
if (response.IsSuccessStatusCode)
{
var jsonString = await response.Content.ReadAsStringAsync();
model = JsonConvert.DeserializeObject<T>(jsonString);
return model;
}
}

Related

new JsonDeserializer(); The type or namespace name jsonDeserializer could not be found (Are you missing a using directive or an assembly reference?)

[TestMethod]
public void TestMethod1()
{
var client = new RestClient("http://localhost:3000");
var request=new RestRequest("posts/{postid}", Method.Get);
request.AddUrlSegment("postid", 1);
var response= client.Execute(request);
var deserialize = new JsonDeserializer();
var output= deserialize.Deserialize<Dictionary<string, string>>(response);
var result = output["author"];
Assert.That(result, Is.EqualTo("Karthik K"), "Author is not correct");
}
}
}
Getting error for below two lines:
var deserialize = new JsonDeserializer(); //Error CS0246 The type or namespace name 'type/namespace' could not be found (are you missing a using directive or an assembly reference?)
var result = output["author"]; // Error CS0021 Cannot apply indexing with [] to an expression of type 'type'
Note: I am using Community edition which is free

Problems downloading web pages

In one controller (MVC ASP.NET) I need to download some web pages, and analyze them.
Currently I'm using Visual Studio 2019, and .NET Framework 4.8.
My code is like this (simplified):
public async void GetHtmlStream(Uri urlAddr)
{
HttpClient client = new HttpClient();
using (HttpResponseMessage Resp = client.GetAsync(urlAddr).Result)
{
using (HttpContent content = Resp.Content)
{
Stream stream = await content.ReadAsStreamAsync().Result;
}
}
}
The line Stream stream = await content.ReadAsStreamAsync().Result; does not compile:
"Error CS1061 'Stream' does not contain definition for 'GetAwaiter' ..."
In a test program, avoiding async and await, i have a line like this:
string result = content.ReadAsStringAsync().Result;
and all works fine.
In the controller, of course nothing works.
I saw a lot of similar issues but I don't understand what should I do to solve the problem.
Try
Stream stream = await content.ReadAsStreamAsync();
instead.

HttpClient object method missing

I am separating some code out of a website and after copying the code behind for the particular page in question, I'm getting an error on the PostAsJsonAsync() line of code:
HttpResponseMessage response = await client.PostAsJsonAsync("api/...", user);
which is in this using statement (added headers as well)
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.Mail;
using System.Threading.Tasks;
//...
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("WebServiceAddress");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = await client.PostAsJsonAsync("api/...", user);
if (response.IsSuccessStatusCode)
{
const string result = "Thank you for your submission.";
return result;
}
//...
}
The error I get says
Error 4 'System.Net.Http.HttpClient'
does not contain a definition for 'PostAsJsonAsync' and no extension
method 'PostAsJsonAsync' accepting a first argument of type 'System.Net.Http.HttpClient'
could be found (are you missing a using directive or an assembly reference?)
even though it works in the former project and was copied straight over from that project in its entirety. Did I forget to add something?
I appreciate any help on the matter.
You will have to add following dependency,
System.Net.Http.Formatting.dll
It should be there in extensions -> assembly.
or
You can add Microsoft.AspNet.WebApi.Client nuget package
I wrote my own extension method as I believe that method is only for older .NET api, and used Newtonsoft JSON serializer:
// Extension method to post a JSON
public static async Task<HttpResponseMessage> PostAsJsonAsync(this HttpClient client, string addr, object obj)
{
var response = await client.PostAsync(addr, new StringContent(
Newtonsoft.Json.JsonConvert.SerializeObject(obj),
Encoding.UTF8, "application/json"));
return response;
}
I had the same error, even with the respective Nuget package installed. What helped me is just this using statement:
using System.Net.Http;

Not Awaitable Type error in my async MSTest Test

this is the first time using async in .NET so I'm totally lost here.
Also I'm trying to use the HttpClient in a unit test to make some calls to my WCF web service. I'm not doing something right because I get "HttpResponseMessage" is not awaitable below. Also it's not recognizing "ReadAsAsync".
I'm not even sure I am doing this right yet
[TestMethod]
public async Task GetTest_RestEndpoint_ListOFInventoryReturnedIsNotNull()
{
// Arrange
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://localhost/Inventory/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// HTTP GET
HttpResponseMessage response = await client.GetAsync("?memberid=323&count=12&pagenumber=1&sortorder=2&eventId=1211");
if (response.IsSuccessStatusCode)
{
InventoryResponse inventoryResponse = await response.Content.ReadAsAsync<InventoryResponse>();
Console.WriteLine("{0}\t${1}\t{2}", inventoryPostResponse.EventID);
}
...
}
Also it's not recognizing "ReadAsAsync".
Here's your primary problem. The ReadAsAsync<T>() extension method is part of the HttpContentExtensions class, which is located in the System.Net.Http.Formatting.dll assembly. Make sure you've added a reference to System.Net.Http.Formatting to your project.

Sending data to a url

I want to send data to a php page, which inserts it in a database. I got the following code from Sending data to php from windows phone from but it shows some errors:
On using: System.Net.WebClient: type used in a using statement
must be implicitly convertible to System.IDisposable.
On UploadString: System.Net.WebClient does not contain a definition for UploadString and no extension method UploadString
accepting a first argument of the type System.Net.WebClient could
be found (are you missing a using directive or an assembly
reference?).
Does anyone have an idea how to fix this?
string URI = "http://www.myurl.com/post.php";
string myParameters = "param1=value1&param2=value2&param3=value3";
using (WebClient wc = new WebClient())
{
wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
string HtmlResult = wc.UploadString(URI, myParameters);
}
http://www.drdobbs.com/windows/writing-your-first-windows-8-app-the-lay/240143752 says HttpClient is replacing WebClient in windows 8 app
Uploadstring uses post method to send data and PostAsync is available in HttpClient which is what you might need.
try something like this.
using System.Net.Http;
//Windows.Web.Http
string URI = "http://www.myurl.com/post.php";
string myParameters = "param1=value1&param2=value2&param3=value3";
sendData(URI,myParameters);
public async void sendData(string URI,string myParameters)
{
using(HttpClient hc = new HttpClient())
{
Var response = await hc.PostAsync(URI,new StringContent (myParameters));
}
}

Categories

Resources