簡體   English   中英

WebSocket in .NET framework 4.6.1 with WebAPI2 controllers

[英]WebSocket in .NET framework 4.6.1 with WebAPI2 controllers

我正在嘗試在我們的 .NET 框架應用程序中使用 WebAPI2 controller 編寫一個新的 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");
    }
}

我以為 websocket 在 .NET 框架 4.5 及以上支持,為什么它會在 .NET 4.6.1 上拋出這個錯誤? 我該如何解決?

僅添加

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM