Reputation: 106912
I've got a very simple need - my C# code needs to connect to a remote server via HTTP and download a string. A trivial GET request, nothing more.
To ensure that my application remains responsive I also want to impose a timeout (say, 3 seconds) on the operation.
My first thought was to use System.Net.WebClient
, but that doesn't support any timeouts.
Then I wanted to try the good old System.Net.HttpWebRequest
, but alas - since .NET 4.5 it's been marked as obsolete!
So, what can I use? I checked out the System.Net.Http
namespace, but it only allows asynchronous usage, forces to use Task
s, and generally only adds a dozen different layers of abstraction without really adding any new functionality (since it uses the same old System.Net.HttpWebRequest
underneath anyway)
I don't want asynchronous stuff, I don't want to involve other threads, I don't want to involve the Tasks framework, I don't want tons of wrappers.
What is the correct way to do this in .NET 4.5?
Upvotes: 10
Views: 2349
Reputation: 26633
Only the constructor is deprecated, not the HttpWebRequest class itself. Use WebRequest.Create to create an instance of HttpWebRequest.
Upvotes: 2
Reputation: 78155
HttpWebRequest
class is not deprecated, only its constructors are.
To cite the documentation:
Do not use the
HttpWebRequest
constructor. Use theWebRequest.Create
method to initialize newHttpWebRequest
objects. If the scheme for the Uniform Resource Identifier (URI) ishttp://
orhttps://
,Create
returns anHttpWebRequest
object.
Upvotes: 14