.NET Framework 4.6.1中WebAPI2控制器WebSocket报错的解决咨询
基于.NET Framework 4.6.1的WebAPI2项目开发WebSocket功能,使用Postman访问本地WebSocket端点时抛出以下异常:
Exception thrown: 'System.InvalidOperationException' in System.Web.dll
An exception of type 'System.InvalidOperationException' occurred in System.Web.dll but was not handled in user code
WebSockets is unsupported in the current application configuration. To enable this, set the following configuration switch in Web.config:<system.web><httpRuntime targetFramework="4.5" /></system.web>
WebSocket实现代码如下:
public class CANCamController : ApiController { [Route("api2.0/CANCam/Connect")] [HttpGet] public HttpResponseMessage Connect() { Debug.WriteLine("Connection request"); if (HttpContext.Current.IsWebSocketRequest) { HttpContext.Current.AcceptWebSocketRequest(ProcessCANCam); } return new HttpResponseMessage(HttpStatusCode.SwitchingProtocols); } private async Task ProcessCANCam(AspNetWebSocketContext context) { WebSocket socket = context.WebSocket; while (true) { ArraySegment<byte> buffer = new ArraySegment<byte>(new byte[1024]); WebSocketReceiveResult result = await socket.ReceiveAsync( buffer, CancellationToken.None); if (socket.State == WebSocketState.Open) { string userMessage = Encoding.UTF8.GetString( buffer.Array, 0, result.Count); userMessage = "You sent: " + userMessage + " at " + DateTime.Now.ToLongTimeString(); buffer = new ArraySegment<byte>( Encoding.UTF8.GetBytes(userMessage)); await socket.SendAsync( buffer, WebSocketMessageType.Text, true, CancellationToken.None); } else { break; } } } [Route("api2.0/CANCam/CheckApi")] [HttpGet] public void CheckApi() { JsonResponse.NewResponse("API is up and running"); } }
明明.NET Framework 4.5及以上支持WebSocket,为何4.6.1版本会出现该报错?应如何解决?
ASP.NET的WebSocket特性不仅依赖.NET Framework版本,还需要通过web.config中的targetFramework属性明确告知运行时启用对应版本的特性。即使项目引用的是4.6.1,如果httpRuntime节点的targetFramework未设置或设置为低于4.5的值,ASP.NET会以兼容旧版本的模式运行,WebSocket这类高版本特性会被禁用。
修改web.config的httpRuntime配置
打开项目的web.config文件,找到<system.web>节点下的<httpRuntime>,设置targetFramework为项目实际使用的.NET Framework版本(这里是4.6.1):<system.web> <httpRuntime targetFramework="4.6.1" /> </system.web>同步compilation节点的targetFramework
确保<compilation>节点的targetFramework也设置为4.6.1,保持配置一致:<system.web> <compilation debug="true" targetFramework="4.6.1" /> <httpRuntime targetFramework="4.6.1" /> </system.web>检查IIS环境支持(如果使用IIS托管)
- 确保使用IIS 8.0及以上版本(对应Windows Server 2012或Windows 8及以上系统)
- 在IIS管理器中,确保已启用WebSocket协议功能:
- 打开服务器管理器 -> 添加角色和功能
- 找到Web服务器(IIS)-> Web服务器 -> 应用程序开发 -> 勾选WebSocket协议
内容的提问来源于stack exchange,提问作者Hrithvik Gadhiya

