WPF上的PCL HttpWebRequest用户代理 [英] PCL HttpWebRequest User-Agent on WPF

查看:164
本文介绍了WPF上的PCL HttpWebRequest用户代理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在我的一个执行很多WebRequests的项目中使用PCL.

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

我必须设置UserAgent,否则我的API将无法接受呼叫.在Windows Phone 8和Windows 8中这很好,因为HttpWebRequest具有Headers属性,因此您可以执行以下操作:

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;

但是在Windows窗体和WPF中,我需要先使用该方法进行设置:

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;

但是PCL不允许这样做,而当我尝试另一种方式时,它只会引发错误:

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

其他信息:必须使用适当的属性或方法来修改"User-Agent"标头.

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

我尝试将WINDOWS_FORMSWPF放入生成条件"中,并使用.UserAgent/.Referer设置if语句,但无济于事.有人遇到这个问题并找到了解决方法吗?

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?

推荐答案

这是一个较晚的回复,但对您或其他访客可能仍然有用.功能:

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

这篇关于WPF上的PCL HttpWebRequest用户代理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆