Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is UserAgent property missing from my HttpWebRequest class?

I was trying to set the value to something from PCL, when I realized that it's missing. This is how my HttpWebRequest class looks like:

#region Assembly System.Net.Requests, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a
// C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETPortable\v4.5\Profile\Profile111\System.Net.Requests.dll
#endregion

using System.IO;

namespace System.Net
{
    //
    // Summary:
    //     Provides an HTTP-specific implementation of the System.Net.WebRequest class.
    public class HttpWebRequest : WebRequest
    {
        //
        // Summary:
        //     Gets or sets the value of the Accept HTTP header.
        //
        // Returns:
        //     The value of the Accept HTTP header. The default value is null.
        public string Accept { get; set; }
        //
        // Summary:
        //     Gets or sets a value that indicates whether to buffer the received from the Internet
        //     resource.
        //
        // Returns:
        //     Returns System.Boolean.true to enable buffering of the data received from the
        //     Internet resource; false to disable buffering. The default is true.
        public virtual bool AllowReadStreamBuffering { get; set; }
        public override string ContentType { get; set; }
        //
        // Summary:
        //     Gets or sets a timeout, in milliseconds, to wait until the 100-Continue is received
        //     from the server.
        //
        // Returns:
        //     Returns System.Int32.The timeout, in milliseconds, to wait until the 100-Continue
        //     is received.
        public int ContinueTimeout { get; set; }
        //
        // Summary:
        //     Gets or sets the cookies associated with the request.
        //
        // Returns:
        //     A System.Net.CookieContainer that contains the cookies associated with this request.
        public virtual CookieContainer CookieContainer { get; set; }
        //
        // Summary:
        //     Gets or sets authentication information for the request.
        //
        // Returns:
        //     An System.Net.ICredentials that contains the authentication credentials associated
        //     with the request. The default is null.
        public override ICredentials Credentials { get; set; }
        //
        // Summary:
        //     Gets a value that indicates whether a response has been received from an Internet
        //     resource.
        //
        // Returns:
        //     true if a response has been received; otherwise, false.
        public virtual bool HaveResponse { get; }
        //
        // Summary:
        //     Specifies a collection of the name/value pairs that make up the HTTP headers.
        //
        // Returns:
        //     A System.Net.WebHeaderCollection that contains the name/value pairs that make
        //     up the headers for the HTTP request.
        //
        // Exceptions:
        //   T:System.InvalidOperationException:
        //     The request has been started by calling the System.Net.HttpWebRequest.GetRequestStream,
        //     System.Net.HttpWebRequest.BeginGetRequestStream(System.AsyncCallback,System.Object),
        //     System.Net.HttpWebRequest.GetResponse, or System.Net.HttpWebRequest.BeginGetResponse(System.AsyncCallback,System.Object)
        //     method.
        public override WebHeaderCollection Headers { get; set; }
        //
        // Summary:
        //     Gets or sets the method for the request.
        //
        // Returns:
        //     The request method to use to contact the Internet resource. The default value
        //     is GET.
        //
        // Exceptions:
        //   T:System.ArgumentException:
        //     No method is supplied.-or- The method string contains invalid characters.
        public override string Method { get; set; }
        //
        // Summary:
        //     Gets the original Uniform Resource Identifier (URI) of the request.
        //
        // Returns:
        //     A System.Uri that contains the URI of the Internet resource passed to the System.Net.WebRequest.Create(System.String)
        //     method.
        public override Uri RequestUri { get; }
        //
        // Summary:
        //     Gets a value that indicates whether the request provides support for a System.Net.CookieContainer.
        //
        // Returns:
        //     Returns System.Boolean.true if a System.Net.CookieContainer is supported; otherwise,
        //     false.
        public virtual bool SupportsCookieContainer { get; }
        //
        // Summary:
        //     Gets or sets a System.Boolean value that controls whether default credentials
        //     are sent with requests.
        //
        // Returns:
        //     true if the default credentials are used; otherwise false. The default value
        //     is false.
        //
        // Exceptions:
        //   T:System.InvalidOperationException:
        //     You attempted to set this property after the request was sent.
        public override bool UseDefaultCredentials { get; set; }

        //
        // Summary:
        //     Cancels a request to an Internet resource.
        public override void Abort();
        //
        // Summary:
        //     Begins an asynchronous request for a System.IO.Stream object to use to write
        //     data.
        //
        // Parameters:
        //   callback:
        //     The System.AsyncCallback delegate.
        //
        //   state:
        //     The state object for this request.
        //
        // Returns:
        //     An System.IAsyncResult that references the asynchronous request.
        //
        // Exceptions:
        //   T:System.Net.ProtocolViolationException:
        //     The System.Net.HttpWebRequest.Method property is GET or HEAD.-or- System.Net.HttpWebRequest.KeepAlive
        //     is true, System.Net.HttpWebRequest.AllowWriteStreamBuffering is false, System.Net.HttpWebRequest.ContentLength
        //     is -1, System.Net.HttpWebRequest.SendChunked is false, and System.Net.HttpWebRequest.Method
        //     is POST or PUT.
        //
        //   T:System.InvalidOperationException:
        //     The stream is being used by a previous call to System.Net.HttpWebRequest.BeginGetRequestStream(System.AsyncCallback,System.Object)-or-
        //     System.Net.HttpWebRequest.TransferEncoding is set to a value and System.Net.HttpWebRequest.SendChunked
        //     is false.-or- The thread pool is running out of threads.
        //
        //   T:System.NotSupportedException:
        //     The request cache validator indicated that the response for this request can
        //     be served from the cache; however, requests that write data must not use the
        //     cache. This exception can occur if you are using a custom cache validator that
        //     is incorrectly implemented.
        //
        //   T:System.Net.WebException:
        //     System.Net.HttpWebRequest.Abort was previously called.
        //
        //   T:System.ObjectDisposedException:
        //     In a .NET Compact Framework application, a request stream with zero content length
        //     was not obtained and closed correctly. For more information about handling zero
        //     content length requests, see Network Programming in the .NET Compact Framework.
        public override IAsyncResult BeginGetRequestStream(AsyncCallback callback, object state);
        //
        // Summary:
        //     Begins an asynchronous request to an Internet resource.
        //
        // Parameters:
        //   callback:
        //     The System.AsyncCallback delegate
        //
        //   state:
        //     The state object for this request.
        //
        // Returns:
        //     An System.IAsyncResult that references the asynchronous request for a response.
        //
        // Exceptions:
        //   T:System.InvalidOperationException:
        //     The stream is already in use by a previous call to System.Net.HttpWebRequest.BeginGetResponse(System.AsyncCallback,System.Object)-or-
        //     System.Net.HttpWebRequest.TransferEncoding is set to a value and System.Net.HttpWebRequest.SendChunked
        //     is false.-or- The thread pool is running out of threads.
        //
        //   T:System.Net.ProtocolViolationException:
        //     System.Net.HttpWebRequest.Method is GET or HEAD, and either System.Net.HttpWebRequest.ContentLength
        //     is greater than zero or System.Net.HttpWebRequest.SendChunked is true.-or- System.Net.HttpWebRequest.KeepAlive
        //     is true, System.Net.HttpWebRequest.AllowWriteStreamBuffering is false, and either
        //     System.Net.HttpWebRequest.ContentLength is -1, System.Net.HttpWebRequest.SendChunked
        //     is false and System.Net.HttpWebRequest.Method is POST or PUT.-or- The System.Net.HttpWebRequest
        //     has an entity body but the System.Net.HttpWebRequest.BeginGetResponse(System.AsyncCallback,System.Object)
        //     method is called without calling the System.Net.HttpWebRequest.BeginGetRequestStream(System.AsyncCallback,System.Object)
        //     method. -or- The System.Net.HttpWebRequest.ContentLength is greater than zero,
        //     but the application does not write all of the promised data.
        //
        //   T:System.Net.WebException:
        //     System.Net.HttpWebRequest.Abort was previously called.
        public override IAsyncResult BeginGetResponse(AsyncCallback callback, object state);
        //
        // Summary:
        //     Ends an asynchronous request for a System.IO.Stream object to use to write data.
        //
        // Parameters:
        //   asyncResult:
        //     The pending request for a stream.
        //
        // Returns:
        //     A System.IO.Stream to use to write request data.
        //
        // Exceptions:
        //   T:System.ArgumentNullException:
        //     asyncResult is null.
        //
        //   T:System.IO.IOException:
        //     The request did not complete, and no stream is available.
        //
        //   T:System.ArgumentException:
        //     asyncResult was not returned by the current instance from a call to System.Net.HttpWebRequest.BeginGetRequestStream(System.AsyncCallback,System.Object).
        //
        //   T:System.InvalidOperationException:
        //     This method was called previously using asyncResult.
        //
        //   T:System.Net.WebException:
        //     System.Net.HttpWebRequest.Abort was previously called.-or- An error occurred
        //     while processing the request.
        public override Stream EndGetRequestStream(IAsyncResult asyncResult);
        //
        // Summary:
        //     Ends an asynchronous request to an Internet resource.
        //
        // Parameters:
        //   asyncResult:
        //     The pending request for a response.
        //
        // Returns:
        //     A System.Net.WebResponse that contains the response from the Internet resource.
        //
        // Exceptions:
        //   T:System.ArgumentNullException:
        //     asyncResult is null.
        //
        //   T:System.InvalidOperationException:
        //     This method was called previously using asyncResult.-or- The System.Net.HttpWebRequest.ContentLength
        //     property is greater than 0 but the data has not been written to the request stream.
        //
        //   T:System.Net.WebException:
        //     System.Net.HttpWebRequest.Abort was previously called.-or- An error occurred
        //     while processing the request.
        //
        //   T:System.ArgumentException:
        //     asyncResult was not returned by the current instance from a call to System.Net.HttpWebRequest.BeginGetResponse(System.AsyncCallback,System.Object).
        public override WebResponse EndGetResponse(IAsyncResult asyncResult);
    }
}

I don't even know what detail to add to the question. Please tell me so I can.

like image 206
nicks Avatar asked Jul 26 '16 14:07

nicks


People also ask

What is Useragent in Httpwebrequest?

It's most commonly used in browsers. You can used the User Agent to specify who you are, and the web server can return a Response with data appropriate for you client.

What is UserAgent header?

The User-Agent request header is a characteristic string that lets servers and network peers identify the application, operating system, vendor, and/or version of the requesting user agent.


2 Answers

It is not clear to me if you are trying to add it or retrieve it so I will update my answer once you specify what you are doing.

The user agent would be included in the Http Header. The class you included has a property named Headers which is where it should be found/set.

For adding: The type WebHeaderCollection has a string indexer which takes the header field as the key. You should be able to add it or retrieve it from there.

request.Headers["User-Agent"] = "your user agent string";

For retrieving you can use the string indexer.

var userAgent = request.Headers["User-Agent"];

Here you can find source code for the type WebHeaderCollection

like image 69
Igor Avatar answered Oct 24 '22 00:10

Igor


According to Documentation on MSDN about HttpWebRequest.UserAgent Property

This is the version information

Version Information

  • .NET Framework Available since 1.1
  • Silverlight Available since 5.0
  • Windows Phone Silverlight Available since 7.0

You will notice that there is no mention of Portable Class Library (PCL) unlike that of the HttpWebRequest Class

Version Information

  • Universal Windows Platform Available since 4.5
  • .NET Framework Available since 1.1
  • Portable Class Library Supported in: portable .NET platforms
  • Silverlight Available since 2.0
  • Windows Phone Silverlight Available since 7.0
  • Windows Phone Available since 8.1

So all that means is that access to the HttpWebRequest.UserAgent Property is not available in PCL

Now although there is a HttpWebRequest.Headers Property available in Portable Class Library, you should note the following remarks from MSDN

Remarks

The Headers collection contains the protocol headers associated with the request. The following table lists the HTTP headers that are not stored in the Headers collection but are either set by the system or set by properties or methods.

They then go on to include User-Agent header in that list.

The Add method throws an ArgumentException if you try to set one of these protected headers.
...
You should not assume that the header values will remain unchanged, because Web servers and caches may change or add headers to a Web request.

Most probably it is set by the system that the PCL is executing on.

Xamarin documentation shows that the property should exist but I believe that this information may be incorrect.

System.Net.HttpWebRequest.UserAgent Property

Gets or sets the value of the User-agent HTTP header.
Syntax
public String UserAgent { get; set; }
Value

    A String containing the value of the HTTP User-agent header. The default value is null.

Remarks
Note: For additional information see section 14.43 of IETF RFC 2616 - HTTP/1.1.
Requirements
Namespace: System.Net
Assembly: System (in System.dll)
Assembly Versions: 1.0.5000.0, 2.0.0.0, 4.0.0.0

You should confirm the platforms that the Portable Class Library targets to make sure that there are no conflicts that would remove the UserAgent property.

PCL : Supported types and members

The types and members that are available in Portable Class Library projects are constrained by several compatibility factors:

  • They must be shared across the targets you selected.

  • The must behave similarly across those targets.

  • They must not be candidates for deprecation.

  • They must make sense in a portable environment, especially when supporting members are not portable.

Here is some documentation from Xamarin

Update

I was able to use HttpClient API to set the User-Agent and make a Get request.

public async Task GetURL(string url) {
    var handler = new HttpClientHandler();
    var httpClient = new HttpClient(handler);
    httpClient.DefaultRequestHeaders.Add("User-Agent", "My Custom User Agent");
    var request = new HttpRequestMessage(HttpMethod.Get, url);
    var response = await httpClient.SendAsync(request);
    //...other code removed for brevity
}
like image 31
Nkosi Avatar answered Oct 24 '22 00:10

Nkosi