- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我需要在 ClientWebSocket
中设置“User-Agent”HTTP header 对象,但这是不可能的。虽然有ClientWebSocket.SetRequestHeader(header,value)
,如果我尝试设置该标题,该方法将失败:System.ArgumentException: This header must be modified using the appropriate property or method.
看着ClientWebSocket
源代码,似乎 MS 人完全忘记了这一点:
// System.Net.WebSockets.ClientWebSocket
private HttpWebRequest CreateAndConfigureRequest(Uri uri)
{
HttpWebRequest httpWebRequest = WebRequest.Create(uri) as HttpWebRequest;
if (httpWebRequest == null)
{
throw new InvalidOperationException(SR.GetString("net_WebSockets_InvalidRegistration"));
}
foreach (string name in this.options.RequestHeaders.Keys)
{
httpWebRequest.Headers.Add(name, this.options.RequestHeaders[name]);
}
if (this.options.RequestedSubProtocols.Count > 0)
{
httpWebRequest.Headers.Add("Sec-WebSocket-Protocol", string.Join(", ", this.options.RequestedSubProtocols));
}
if (this.options.UseDefaultCredentials)
{
httpWebRequest.UseDefaultCredentials = true;
}
else
{
if (this.options.Credentials != null)
{
httpWebRequest.Credentials = this.options.Credentials;
}
}
if (this.options.InternalClientCertificates != null)
{
httpWebRequest.ClientCertificates = this.options.InternalClientCertificates;
}
httpWebRequest.Proxy = this.options.Proxy;
httpWebRequest.CookieContainer = this.options.Cookies;
this.cts.Token.Register(new Action<object>(this.AbortRequest), httpWebRequest, false);
return httpWebRequest;
}
httpWebRequest.UserAgent
)。
最佳答案
不可能。我创建了一个允许设置该标题的类的分支:
public class ClientWebSocketOptions2
{
public int ReceiveBufferSize { get; set; }
public int SendBufferSize { get; set; }
public TimeSpan KeepAliveInterval { get; set; }
public Dictionary<String,String> RequestHeaders { get; private set; }
public List<String> RequestedSubProtocols { get; private set; }
public bool UseDefaultCredentials { get; set; }
public ICredentials Credentials { get; set; }
public X509CertificateCollection InternalClientCertificates { get; set; }
public IWebProxy Proxy { get; set; }
public CookieContainer Cookies { get; set; }
private ArraySegment<byte>? buffer;
public ClientWebSocketOptions2()
{
ReceiveBufferSize = 16384;
SendBufferSize = 16384;
KeepAliveInterval = WebSocket.DefaultKeepAliveInterval;
RequestedSubProtocols = new List<string>();
RequestHeaders = new Dictionary<string, string>();
this.Proxy = WebRequest.DefaultWebProxy;
}
public ArraySegment<byte> GetOrCreateBuffer()
{
if (!this.buffer.HasValue)
{
this.buffer = new ArraySegment<byte>?(WebSocket.CreateClientBuffer(this.ReceiveBufferSize, this.SendBufferSize));
}
return this.buffer.Value;
}
internal static string GetSecWebSocketAcceptString(string secWebSocketKey)
{
string result;
using (SHA1 sHA = SHA1.Create())
{
string s = secWebSocketKey + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
byte[] bytes = Encoding.UTF8.GetBytes(s);
result = Convert.ToBase64String(sHA.ComputeHash(bytes));
}
return result;
}
}
public sealed class ClientWebSocket2 : WebSocket
{
private readonly ClientWebSocketOptions2 options;
private WebSocket innerWebSocket;
private readonly CancellationTokenSource cts;
private int state;
private const int created = 0;
private const int connecting = 1;
private const int connected = 2;
private const int disposed = 3;
public ClientWebSocketOptions2 Options
{
get
{
return this.options;
}
}
public override WebSocketCloseStatus? CloseStatus
{
get
{
if (this.innerWebSocket != null)
{
return this.innerWebSocket.CloseStatus;
}
return null;
}
}
public override string CloseStatusDescription
{
get
{
if (this.innerWebSocket != null)
{
return this.innerWebSocket.CloseStatusDescription;
}
return null;
}
}
public override string SubProtocol
{
get
{
if (this.innerWebSocket != null)
{
return this.innerWebSocket.SubProtocol;
}
return null;
}
}
public override WebSocketState State
{
get
{
if (this.innerWebSocket != null)
{
return this.innerWebSocket.State;
}
switch (this.state)
{
case 0:
return WebSocketState.None;
case 1:
return WebSocketState.Connecting;
case 3:
return WebSocketState.Closed;
}
return WebSocketState.Closed;
}
}
public ClientWebSocket2()
{
this.state = 0;
this.options = new ClientWebSocketOptions2();
this.cts = new CancellationTokenSource();
}
public Task ConnectAsync(Uri uri, CancellationToken cancellationToken)
{
if (uri == null)
{
throw new ArgumentNullException("uri");
}
if (!uri.IsAbsoluteUri)
{
throw new ArgumentException("net_uri_NotAbsolute");
}
if (String.IsNullOrWhiteSpace(uri.Scheme) || (!uri.Scheme.Equals("ws", StringComparison.OrdinalIgnoreCase) && !uri.Scheme.Equals("wss", StringComparison.OrdinalIgnoreCase)))
{
throw new ArgumentException("net_WebSockets_Scheme");
}
int num = Interlocked.CompareExchange(ref this.state, 1, 0);
if (num == 3)
{
throw new ObjectDisposedException(base.GetType().FullName);
}
if (num != 0)
{
throw new InvalidOperationException("net_WebSockets_AlreadyStarted");
}
return this.ConnectAsyncCore(uri, cancellationToken);
}
public override Task SendAsync(ArraySegment<byte> buffer, WebSocketMessageType messageType, bool endOfMessage, CancellationToken cancellationToken)
{
this.ThrowIfNotConnected();
return this.innerWebSocket.SendAsync(buffer, messageType, endOfMessage, cancellationToken);
}
public override Task<WebSocketReceiveResult> ReceiveAsync(ArraySegment<byte> buffer, CancellationToken cancellationToken)
{
this.ThrowIfNotConnected();
return this.innerWebSocket.ReceiveAsync(buffer, cancellationToken);
}
public override Task CloseAsync(WebSocketCloseStatus closeStatus, string statusDescription, CancellationToken cancellationToken)
{
this.ThrowIfNotConnected();
return this.innerWebSocket.CloseAsync(closeStatus, statusDescription, cancellationToken);
}
public override Task CloseOutputAsync(WebSocketCloseStatus closeStatus, string statusDescription, CancellationToken cancellationToken)
{
this.ThrowIfNotConnected();
return this.innerWebSocket.CloseOutputAsync(closeStatus, statusDescription, cancellationToken);
}
public override void Abort()
{
if (this.state == 3)
{
return;
}
if (this.innerWebSocket != null)
{
this.innerWebSocket.Abort();
}
this.Dispose();
}
public override void Dispose()
{
int num = Interlocked.Exchange(ref this.state, 3);
if (num == 3)
{
return;
}
this.cts.Cancel(false);
this.cts.Dispose();
if (this.innerWebSocket != null)
{
this.innerWebSocket.Dispose();
}
}
static ClientWebSocket2()
{
WebSocket.RegisterPrefixes();
}
private async Task ConnectAsyncCore(Uri uri, CancellationToken cancellationToken)
{
HttpWebResponse httpWebResponse = null;
CancellationTokenRegistration cancellationTokenRegistration = default(CancellationTokenRegistration);
try
{
HttpWebRequest httpWebRequest = this.CreateAndConfigureRequest(uri);
cancellationTokenRegistration = cancellationToken.Register(new Action<object>(this.AbortRequest), httpWebRequest, false);
httpWebResponse = ((await httpWebRequest.GetResponseAsync()) as HttpWebResponse);
string subProtocol = this.ValidateResponse(httpWebRequest, httpWebResponse);
this.innerWebSocket = WebSocket.CreateClientWebSocket(httpWebResponse.GetResponseStream(), subProtocol, this.options.ReceiveBufferSize, this.options.SendBufferSize, this.options.KeepAliveInterval, false, this.options.GetOrCreateBuffer());
if (Interlocked.CompareExchange(ref this.state, 2, 1) != 1)
{
throw new ObjectDisposedException(base.GetType().FullName);
}
}
catch (WebException innerException)
{
this.ConnectExceptionCleanup(httpWebResponse);
WebSocketException ex = new WebSocketException("net_webstatus_ConnectFailure", innerException);
throw ex;
}
catch (Exception e)
{
this.ConnectExceptionCleanup(httpWebResponse);
throw;
}
finally
{
cancellationTokenRegistration.Dispose();
}
}
private void ConnectExceptionCleanup(HttpWebResponse response)
{
this.Dispose();
if (response != null)
{
response.Dispose();
}
}
private HttpWebRequest CreateAndConfigureRequest(Uri uri)
{
HttpWebRequest httpWebRequest = WebRequest.Create(uri) as HttpWebRequest;
if (httpWebRequest == null)
{
throw new InvalidOperationException("net_WebSockets_InvalidRegistration");
}
foreach (string name in this.options.RequestHeaders.Keys)
{
if (name.Equals("user-agent", StringComparison.OrdinalIgnoreCase))
{
httpWebRequest.UserAgent = this.options.RequestHeaders[name];
}
else
httpWebRequest.Headers.Add(name, this.options.RequestHeaders[name]);
}
if (this.options.RequestedSubProtocols.Count > 0)
{
httpWebRequest.Headers.Add("Sec-WebSocket-Protocol", string.Join(", ", this.options.RequestedSubProtocols));
}
if (this.options.UseDefaultCredentials)
{
httpWebRequest.UseDefaultCredentials = true;
}
else
{
if (this.options.Credentials != null)
{
httpWebRequest.Credentials = this.options.Credentials;
}
}
if (this.options.InternalClientCertificates != null)
{
httpWebRequest.ClientCertificates = this.options.InternalClientCertificates;
}
httpWebRequest.Proxy = this.options.Proxy;
httpWebRequest.CookieContainer = this.options.Cookies;
this.cts.Token.Register(new Action<object>(this.AbortRequest), httpWebRequest, false);
return httpWebRequest;
}
private string ValidateResponse(HttpWebRequest request, HttpWebResponse response)
{
if (response.StatusCode != HttpStatusCode.SwitchingProtocols)
{
throw new WebSocketException("net_WebSockets_Connect101Expected");
}
string text = response.Headers["Upgrade"];
if (!string.Equals(text, "websocket", StringComparison.OrdinalIgnoreCase))
{
throw new WebSocketException("net_WebSockets_InvalidResponseHeader");
}
string text2 = response.Headers["Connection"];
if (!string.Equals(text2, "Upgrade", StringComparison.OrdinalIgnoreCase))
{
throw new WebSocketException("net_WebSockets_InvalidResponseHeader");
}
string text3 = response.Headers["Sec-WebSocket-Accept"];
string secWebSocketAcceptString = ClientWebSocketOptions2.GetSecWebSocketAcceptString(request.Headers["Sec-WebSocket-Key"]);
if (!string.Equals(text3, secWebSocketAcceptString, StringComparison.OrdinalIgnoreCase))
{
throw new WebSocketException("net_WebSockets_InvalidResponseHeader");
}
string text4 = response.Headers["Sec-WebSocket-Protocol"];
if (!string.IsNullOrWhiteSpace(text4) && this.options.RequestedSubProtocols.Count > 0)
{
bool flag = false;
foreach (string current in this.options.RequestedSubProtocols)
{
if (string.Equals(current, text4, StringComparison.OrdinalIgnoreCase))
{
flag = true;
break;
}
}
if (!flag)
{
throw new WebSocketException("net_WebSockets_AcceptUnsupportedProtocol");
}
}
if (!string.IsNullOrWhiteSpace(text4))
{
return text4;
}
return null;
}
private void AbortRequest(object obj)
{
HttpWebRequest httpWebRequest = (HttpWebRequest)obj;
httpWebRequest.Abort();
}
private void ThrowIfNotConnected()
{
if (this.state == 3)
{
throw new ObjectDisposedException(base.GetType().FullName);
}
if (this.state != 2)
{
throw new InvalidOperationException("net_WebSockets_NotConnected");
}
}
}
关于.net - 在 ClientWebSocket 中设置 "User-Agent"HTTP header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22635663/
我正在使用 System.Net.WebSockets.ClientWebSocket在 .NET 4.7 应用程序中,并且在尝试使依赖于它的代码可测试时遇到问题。 ClientWebSocket是一
我正在 Xamarin.Forms 中编写一个面向 .Net Standard 2.1 的应用程序,主要专注于 Android 构建。 我有一些 websocket 客户端代码可以连接到我的安全自签名
我目前正在研究使用 websockets 在客户端/代理和服务器之间进行通信,并决定为此目的使用 C#。尽管我之前使用过 Websockets 和 C#,但这是我第一次同时使用这两者。第一次尝试使用以
我在 Osx 上实现安全的网络套接字客户端时遇到问题。我正在使用 System.Net.WebSockets 中的 ClientWebSocket。这是一些测试代码: static async
document不清楚System.Net.WebSockets.ClientWebSocket的线程安全性类(class)。 拨打 SendAsync 安全吗?多个线程同时调用的方法? 最佳答案 它
客户端环境是 Xamarin Android Native TLS 1.2 SSL/TLS 实现(boringssl aka btls),使用 System.Net.WebSockets.Client
我已经按照 this 在 .net 核心中构建了一个 WebSocket Web 应用程序和 this或 this教程。现在我正在尝试使用 Microsoft.AspNetCore.TestHost
我正在使用 System.Net.WebSockets.ClientWebSocket 创建一个 C# WebSocket 客户端以连接到我不拥有源代码的服务器。到目前为止一切正常,但我希望“正确”断
我在 Windows 上运行以下 websocket 客户端代码,一切正常 - 正如预期的那样。但是,如果代码是为 linux-arm 发布并复制到 RaspberryPi3(在 Raspian 下运
我需要在 ClientWebSocket 中设置“User-Agent”HTTP header 对象,但这是不可能的。虽然有ClientWebSocket.SetRequestHeader(heade
我尝试在 .Net 中使用谷歌搜索支持 SSL(和代理)的 echo 客户端的示例代码,我有不支持 SSL 和代理的简单 echo 客户端,但我需要已通过证书实现 SSL 的客户端(自签名) 我正在使
我想为连接到 Web 套接字服务器时使用的 Web 套接字客户端指定 ssl 证书。 唯一constructor对于 System.Net.WebSockets.ClientWebSocket有 0
我正在尝试实现WebSocket,但是每次尝试阅读它时,都会引发“远程方在未完成关闭握手的情况下关闭了WebSocket连接”。错误。 这是我的代码: string url = "wss://ws.u
网络套接字是我的同事用 javascript 编写的。我成功连接了。首先,我必须使用测试帐户登录应用程序。我必须通过 json 发送电子邮件和密码。我已经使用 NuGet 安装了 Json.Net 数
使用 ClientWebSocket.SetHeader 的明显答案会引发异常,因为它是 protected header : System.ArgumentException occurred M
我是一名优秀的程序员,十分优秀!