【问题标题】:WebSocket in .NET framework 4.6.1 with WebAPI2 controllers带有 WebAPI2 控制器的 .NET 框架 4.6.1 中的 WebSocket
【发布时间】:2023-02-04 00:40:13
【问题描述】:

我正在尝试在我们的 .NET 框架应用程序中编写一个带有 WebAPI2 控制器的新 WebSocket。当我尝试在本地主机上使用 Postman 访问 websocket 端点时,出现以下错误,指出 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>
For more information, see http://go.microsoft.com/fwlink/?LinkId=252465

我的 Websocket 的实现方式如 https://www.codeproject.com/Articles/618032/Using-WebSocket-in-NET-4-5-Part-2 所示。代码如下所示:

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,为什么它会在 .NET 4.6.1 上抛出此错误?我该如何解决 ?

【问题讨论】:

    标签: c# .net websocket asp.net-web-api2


    【解决方案1】:

    仅添加

    <system.web>
      <httpRuntime targetFramework="4.6" />
    </system.web>
    

    【讨论】:

      猜你喜欢
      • 2017-08-11
      • 1970-01-01
      • 1970-01-01
      • 2015-08-04
      • 1970-01-01
      • 2018-03-21
      • 1970-01-01
      • 2012-05-02
      • 2017-07-10
      相关资源
      最近更新 更多