Search code examples
c#httpwebrequestuser-agentportable-class-library

PCL HttpWebRequest User-Agent on WPF


I'm using a PCL on a project of mine that does alot of WebRequests.

I have to set a UserAgent or my API won't accept the call. This is fine in Windows Phone 8 and Windows 8 because the HttpWebRequest has a Headers property so you can just do:

var request = (HttpWebRequest)WebRequest.Create(cUrlLogin);
request.Headers[HttpRequestHeader.UserAgent] = cUserAgent;
request.Headers[HttpRequestHeader.Referer] = cUrlHalo;

But in Windows Forms and WPF, I need to use the method to set it, before I just did:

var request = (HttpWebRequest)WebRequest.Create(cUrlLogin);
request.UserAgent = cUserAgent;
request.Referer = cUrlHalo;

But this isn't allowed by the PCL, and when I try the other way it just throws the error:

Additional information: The 'User-Agent' header must be modified using the appropriate property or method.

I've tried putting WINDOWS_FORMS or WPF in the Build Conditionals, and putting an if statement around setting it using the .UserAgent/.Referer, but to no avail. Has anybody run into this and found a workaround?


Solution

  • This is a late response, but may still be useful for either you or another visitor. The function:

    public void SetHeader(HttpWebRequest Request, string Header, string Value) {
        // Retrieve the property through reflection.
        PropertyInfo PropertyInfo = Request.GetType().GetProperty(Header.Replace("-", string.Empty));
        // Check if the property is available.
        if (PropertyInfo != null) {
            // Set the value of the header.
            PropertyInfo.SetValue(Request, Value, null);
        } else {
            // Set the value of the header.
            Request.Headers[Header] = Value;
        }
    }
    

    This attempts to set a property, and defaults to a header after that. Usage examples:

    // Initialize a new instance of the HttpWebRequest class.
    HttpWebRequest Request = WebRequest.Create(Address) as HttpWebRequest;
    // Set the value of the user agent.
    SetHeader(Request, "User-Agent", "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)");
    // Set the value of the referer.
    SetHeader(Request, "Referer", Referer.AbsoluteUri);