I have the following code in my portable class library. But it gives error that
System.Net.HttpWebRequest
does not contain a definition forGetResponse()
.
public async Task<object> GetStateByUserId(string userID)
{
HttpWebRequest request;
Stream receiveStream;
StreamReader readStream;
request =(HttpWebRequest)CreateGetWebRequest("state/uid/"+userID);
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) {
receiveStream = response.GetResponseStream ();
readStream = new StreamReader(receiveStream);
string str = readStream.ReadToEnd().ToString();
s = JsonConvert.DeserializeObject<state>(str);
return s;
}
}
Anyone know why it is so?
If you look at the documentation for
GetResponse()
and compare it withGetResponseAsync()
, you'll notice that in Version information, for example Windows Store apps are missing forGetResponse()
and other versions of the framework are missing inGetResponseAsync()
.Depending on the versions of the framework you chose for your PCL, you might be able to use
GetResponseAsync()
directly (for example if you chose .Net 4.5 and Windows Store, but nothing else).If you need some of the frameworks that don't support
GetResponseAsync()
out of the box, then I think the best solution here is to use the Microsoft.Bcl.Async NuGet package, which will allow you to useGetResponseAsync()
in other versions of the framework.Also, switching to
GetResponseAsync()
means you will need to useawait
to get the value, which also means making this method and all methods that call itasync
. (Though confusingly, it seems you already switched toasync
without usingawait
, which doesn't make much sense.)If you are writing for targetting the portable class library, you will have to use the asynchronous methods as GetResponse is not available.
Instead you have to use BeginGetReponse and EndGetResponse.
In your case, this could look like this:
If you are using .NET 4.5, you can do it like this: