在.net 4.5中使用ClientWebSocket时如何设置User-Agent和Referer标头? [英] How can I set User-Agent and Referer headers when using ClientWebSocket in .net 4.5?

查看:742
本文介绍了在.net 4.5中使用ClientWebSocket时如何设置User-Agent和Referer标头?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 ClientWebSocket.SetHeader 的明显答案将引发异常,因为它是受保护的标头:

The obvious answer of using ClientWebSocket.SetHeader throws an exception because it's a protected header:


System.ArgumentException occurred
  Message=The 'User-Agent' header must be modified using the appropriate property or method.
Parameter name: name
  ParamName=name
  StackTrace:
       at System.Net.WebHeaderCollection.ThrowOnRestrictedHeader(String headerName)

该异常字符串建议在 ClientWebSocket 本身上使用属性/方法,但是我找不到任何这样的属性/方法。似乎此异常是为 HttpWebRequest 类设计的,该类实际上具有这种属性。

The exception string suggests using a property/method on the ClientWebSocket itself but I can't find any such property/method. It seems this exception was designed for the HttpWebRequest class, which actually has such property.

该代码没有无法正常工作:

The code, which doesn't work:

ClientWebSocket socket = new ClientWebSocket();
// Will throw
socket.Options.SetRequestHeader("User-Agent", "SomeUserAgentString");
// Will throw
socket.Options.SetRequestHeader("Referer", "SomeReferer"]);


推荐答案

看起来您将无法设置这些属性,至少现在不是。您可能可以通过反射来实现。

It doesn't look like you'll be able to set those properties, at least not right now. You might be able to do it via reflection.

如果仔细观察堆栈跟踪,您会发现throwing方法是 System.Net.WebHeaderCollection.ThrowOnRestrictedHeader System.Net .WebHeaderCollection 是专门用于处理HTTP标头的名称值集合。如果您查看备注部分,则会看到以下内容:

If you look closely at your stack trace, you'll see that the throwing method is System.Net.WebHeaderCollection.ThrowOnRestrictedHeader. System.Net.WebHeaderCollection is a specialized name value collection designed to deal with HTTP headers. If you look at the remarks section, you'll see the following:


一些常见的标头被认为是受限制的,或者直接由API(例如 Content-Type )或受系统保护并且无法更改。

Some common headers are considered restricted and are either exposed directly by the API (such as Content-Type) or protected by the system and cannot be changed.

列表同时具有 User-Agent Referer 属性列为受保护的标头,并且由于 ClientWebSocket 不会公开它。

The list has both the User-Agent and Referer properties listed as protected headers and cannot be set since the ClientWebSocket does not expose it.

所有这些,但是,如果您绝对需要进行设置标头中,您需要找到 ClientWebSocketOptions 的私有引用 WebHeaderCollection (显示为 ClientWebSocket 上的> Options 属性),然后调用受保护的 AddWithoutValidate 方法来设置标题。

All that being said, though, if you absolutely need to set those headers, you'll need to find the private reference WebHeaderCollection of your ClientWebSocketOptions (exposed as the Options property on your ClientWebSocket) and call the protected AddWithoutValidate method to set the headers.

这篇关于在.net 4.5中使用ClientWebSocket时如何设置User-Agent和Referer标头?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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