I am trying to write a new WebSocket with a WebAPI2 controller in our .NET framework application. When I try to hit the websocket endpoint using Postman on localhost, I get the following error saying WebSocket is unsupported.
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
My Websocket was implemented as shown on https://www.codeproject.com/Articles/618032/Using-WebSocket-in-NET-4-5-Part-2 . The code looks like follows:
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");
}
}
I thought websocket was supported on .NET framework 4.5 and above, why would it throw this error on .NET 4.6.1 ? How do I fix this ?