0

I use my webapi in my intranet with works fine and deactivated any cors policy because i dont need them.

Now i want also to have a websocket into my iis app but when running it only localhost works as excepted and all other request comes into an cors error

Global.asax.cs:

public class WebApiApplication : System.Web.HttpApplication
    {
        private static readonly ILogger Logger = Log.ForContext<WebApiApplication>();

        protected void Application_Start()
        {
            Logger.Debug("In Application_Start");

            EnableCorsAttribute corsAttribute = new EnableCorsAttribute("*", "*", "*");
            AreaRegistration.RegisterAllAreas();
            GlobalConfiguration.Configure(WebApiConfig.Register);
            GlobalConfiguration.Configuration.EnableCors(corsAttribute);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            // NEW PART START:Add WebSocket route handler
            string baseAddress = "http://*:9999/websocket/";
            HttpListener listener = new HttpListener();
            listener.Prefixes.Add(baseAddress);
            listener.Start();

            // Handle WebSocket upgrade requests
            listener.BeginGetContext(HandleWebSocketRequest, listener);
            //NEW PART END
            Logger.Information("App started !");
        }
        // NEW PART
        private async Task HandleWebSocket(HttpListenerContext context)
        {
            HttpListenerWebSocketContext webSocketContext = null;
            try
            {
                webSocketContext = await context.AcceptWebSocketAsync(subProtocol: null);

                // WebSocket connection established
                WebSocket webSocket = webSocketContext.WebSocket;

                // Handle WebSocket communication
                await HandleWebSocketCommunication(webSocket);
            }
            catch (Exception ex)
            {
                // Handle WebSocket upgrade exception
                Console.WriteLine($"WebSocket upgrade error: {ex.Message}");
                if (webSocketContext != null)
                {
                    webSocketContext.WebSocket.CloseAsync(WebSocketCloseStatus.InternalServerError, "Internal Server Error", CancellationToken.None).Wait();
                }
            }
        }
        // NEW PART
        private async Task HandleWebSocketCommunication(WebSocket webSocket)
        {
            var buffer = new byte[1024 * 4];
            try
            {
                while (webSocket.State == WebSocketState.Open)
                {
                    // Receive a message from the client
                    WebSocketReceiveResult result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);

                    if (result.MessageType == WebSocketMessageType.Text)
                    {
                        // Handle text message
                        string message = Encoding.UTF8.GetString(buffer, 0, result.Count);
                        Console.WriteLine($"Received message: {message}");

                        // React to the received message
                        await ReactToMessage(webSocket, message);
                    }
                    else if (result.MessageType == WebSocketMessageType.Close)
                    {
                        // Handle close message
                        await webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "", CancellationToken.None);
                    }
                }
            }
            catch (WebSocketException ex)
            {
                // Handle WebSocket communication exception
                Console.WriteLine($"WebSocket communication error: {ex.Message}");
            }
            finally
            {
                // Close WebSocket connection
                if (webSocket.State == WebSocketState.Open)
                {
                    await webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "", CancellationToken.None);
                }
                webSocket.Dispose();
            }
        }
        // NEW PART
        private async Task ReactToMessage(WebSocket webSocket, string message)
        {
            // Implement your logic to react to the received message
            // For example, you could process the message and send a response back to the client
            string responseMessage = $"Received your message: {message}";
            byte[] responseBuffer = Encoding.UTF8.GetBytes(responseMessage);
            await webSocket.SendAsync(new ArraySegment<byte>(responseBuffer), WebSocketMessageType.Text, true, CancellationToken.None);
        }
        // NEW PART
        private void HandleWebSocketRequest(IAsyncResult result)
        {
            HttpListener listener = (HttpListener)result.AsyncState;
            HttpListenerContext context = listener.EndGetContext(result);

            if (context.Request.IsWebSocketRequest)
            {
                // Upgrade HTTP connection to WebSocket
                HandleWebSocket(context);
            }
            else
            {
                // Handle other HTTP requests
                // For example, you can return a 404 response
                context.Response.StatusCode = 404;
                context.Response.Close();
            }

            // Continue listening for incoming requests
            listener.BeginGetContext(HandleWebSocketRequest, listener);
        }


        protected void Application_End(object sender, EventArgs e)
        {
            Logger.Debug("In Application_End");
            ApplicationShutdownReason shutdownReason = System.Web.Hosting.HostingEnvironment.ShutdownReason;
        }
    }

Maybe someone can explain me where my error is.

1 Answer 1

0

Browsers usually send a CORS preflight request to see if the CORS protocol is understood by the server. If the server doesn’t respond with CORS headers, then the request will be denied by the browser.

In your local environment you are directly accessing your ASP.NET application, so all works well there. But in case of IIS, which is a reverse proxy for your application, it can respond to requests without any call being issued to your ASP.NET application and that depends on how IIS is configured to host your application.

The closest thing I found that can solve this problem is described in this thread: IIS hijacks CORS Preflight OPTIONS request

1
  • But also if i use localhost:9999 as url Definition in the Code and run it on iis it workes Fine on the iis Server and i can Connect from the iis Server to it but Only from there. Web api Runs Fine as before. If i Change it back to *:9999 Nothing Works anymore
    – Yusuf Keks
    Commented Apr 7, 2024 at 6:27

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.