PCL HttpWebRequest User-Agent on WPF

感情迁移 提交于 2019-12-11 05:53:04

问题


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?


回答1:


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);



回答2:


I ended up having to just create 2 libraries of pretty much the same code. One library as a Class Library for Win32, and a Portable Class Library for WinRT.



来源:https://stackoverflow.com/questions/14534081/pcl-httpwebrequest-user-agent-on-wpf

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!