I am trying to convert an existing app to a Metro UI app in VS 11 Developer Preview. This means running against the WinRT runtime (correct me if I'm wrong). This runs on the Windows 8 Developer Preview.
I need to call a REST API, which requires a specific user-agent to be set. This doesn't seem to be possible in WInRT. I have the following original code:
_request = WebRequest.CreateHttp(url);
_request.UserAgent = UserAgent;
But the UserAgent property is not defined for HttpWebRequest. I also tried:
_request.Headers["User-Agent"] = UserAgent;
This results in a runtime exception: System.ArgumentException: This header must be modified using the appropriate property or method.
How can I modify the User-Agent header ?
After some tinkering around, I have now worked out how to do this in WinRT. The HttpWebRequest API has changed in this version to be a lot poorer than in the full .NET Framework. However, I can send a request with the new HttpClient
API, which will allow me to send the user-agent header:
var req = new HttpClient(handler)
var message = new HttpRequestMessage(HttpMethod.Get, url);
message.Headers.Add("User-Agent", "myCustomUserAgent");
var response = await req.SendAsync(message);
Just to note that in Windows 10 it is possible to do it exactly like in the example in your question.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With