gpt4 book ai didi

c# - 在 .net 4.5 中使用 ClientWebSocket 时如何设置 User-Agent 和 Referer header ?

转载 作者:太空狗 更新时间:2023-10-29 23:32:26 29 4
gpt4 key购买 nike

使用 ClientWebSocket.SetHeader 的明显答案会引发异常,因为它是 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)

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

最佳答案

看起来您无法设置这些属性,至少现在不能。您可能可以通过反射(reflection)来做到这一点。

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

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-AgentReferer列为 protected header 的属性,自 ClientWebSocket 以来无法设置不暴露它。

尽管如此,如果您绝对需要设置这些 header ,您将需要找到私有(private)引用 WebHeaderCollection你的ClientWebSocketOptions (在您的 Options 上显示为 ClientWebSocket 属性)并调用 protected AddWithoutValidate 设置标题的方法。

关于c# - 在 .net 4.5 中使用 ClientWebSocket 时如何设置 User-Agent 和 Referer header ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15894844/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com