Home > Blockchain >  C# HTTP Error 400 - Invalid Hostname Simple Http Listener
C# HTTP Error 400 - Invalid Hostname Simple Http Listener

Time:09-10

using System.Net;
using System.Text;

namespace HttpServer
{
    class Program
    {
        // Main method
        static void Main()
        {
            using var listener = new HttpListener();
            listener.Prefixes.Add("http://localhost:10060/");

            listener.Start();

            Console.WriteLine("Listening on port 10060...");

            // Request handler
            while (true)
            {
                HttpListenerContext context = listener.GetContext();
                HttpListenerRequest req = context.Request;

                Console.WriteLine($"Received request for {req.Url}");

                // TODO: Login stuff
                Uri? url = req.Url;
                if (url.ToString() == "http://localhost:10060/login")
                {
                    using HttpListenerResponse resp = context.Response;
                    resp.Headers.Set("Content-Type", "text/plain");

                    string data = "Hello there!";
                    byte[] buffer = Encoding.UTF8.GetBytes(data);
                    resp.ContentLength64 = buffer.Length;

                    using Stream ros = resp.OutputStream;
                    ros.Write(buffer, 0, buffer.Length);
                }

            }

        }
    }
}

The above code is a simple http server that listens for requests. The above code works when going to localhost:10060 in the browser. However, I want to access this server via the machine's IP address on the same network through a different device. When doing so, it results in a bad request due to the invalid hostname. Is there a way to fix this?

CodePudding user response:

try using the ip address instead of localhost. or try *:10060

CodePudding user response:

In another machine try to modify firewall rule to allow port 80. 1.Windows defender firewall with advance security on local Computer. 2.Inbound rules 3.New Rule 4.Select the port, Next, TCP, specific local port, type 80 5.Allow the connection and save the rule.

Let us know if this worked.

CodePudding user response:

It's not a good practice to use http locations other than a string, it's good to store them in a string/var and put them later, at least for me it's a good practice. Also check that .NET or your own project is not blocking anything, if so you will have to add a builder.services. This can be in program.cs, web.config or startup.cs, in any of these if I'm not mistaken, depending on your version. And if the access gives "Denied" check the version of the nuget package or reference you are using etc... see if there is nothing pending

  •  Tags:  
  • c#
  • Related