8

I am looking to create a simple webpage using C# Windows Forms Application, or a C# Console application.

Running the application will begin hosting a web page at:

http://localhost:3070/somepage

I have read a little bit on MSDN about using endpoints, however being self-taught, this isn't making a ton of sense to me...

In short, this program, when running will display some text on a webpage at localhost:3070.

Sorry for such a vague question, however my hour(s) of searching for a decent tutorial haven't yielded any understandable results...

Thanks for your time!

JesterBaze
  • 130
  • 2
  • 2
  • 11

2 Answers2

9

2020 Update:

Original answer at the bottom.

Kestrel and Katana are now a thing and I would strongly recommend you look into those things as well as OWIN


Original Answer:

You will want to look into creating an HttpListener, you can add prefixes to the listener such as Listener.Prefixes.Add("http://+:3070/") which will bind it to the port your wanting.

A simple console app: Counting the requests made

using System;
using System.Net;
using System.Text;

namespace TestServer
{
    class ServerMain
    {
        // To enable this so that it can be run in a non-administrator account:
        // Open an Administrator command prompt.
        // netsh http add urlacl http://+:8008/ user=Everyone listen=true
        
        const string Prefix = "http://+:3070/";
        static HttpListener Listener = null;
        static int RequestNumber = 0;
        static readonly DateTime StartupDate = DateTime.UtcNow;

        static void Main(string[] args)
        {
            if (!HttpListener.IsSupported)
            {
                Console.WriteLine("HttpListener is not supported on this platform.");
                return;
            }
            using (Listener = new HttpListener())
            {
                Listener.Prefixes.Add(Prefix);
                Listener.Start();
                // Begin waiting for requests.
                Listener.BeginGetContext(GetContextCallback, null);
                Console.WriteLine("Listening. Press Enter to stop.");
                Console.ReadLine();
                Listener.Stop();
            }
        }

        static void GetContextCallback(IAsyncResult ar)
        {
            int req = ++RequestNumber;

            // Get the context
            var context = Listener.EndGetContext(ar);

            // listen for the next request
            Listener.BeginGetContext(GetContextCallback, null);

            // get the request
            var NowTime = DateTime.UtcNow;

            Console.WriteLine("{0}: {1}", NowTime.ToString("R"), context.Request.RawUrl);

            var responseString = string.Format("<html><body>Your request, \"{0}\", was received at {1}.<br/>It is request #{2:N0} since {3}.",
                context.Request.RawUrl, NowTime.ToString("R"), req, StartupDate.ToString("R"));

            byte[] buffer = Encoding.UTF8.GetBytes(responseString);
            // and send it
            var response = context.Response;
            response.ContentType = "text/html";
            response.ContentLength64 = buffer.Length;
            response.StatusCode = 200;
            response.OutputStream.Write(buffer, 0, buffer.Length);
            response.OutputStream.Close();
        }
    }
}

And for extra credit, try adding it to the services on your computer!

Community
  • 1
  • 1
Oxymoron
  • 1,380
  • 2
  • 19
  • 47
  • To add on @Oxymoron post, in order for the listener to open that port the application must with admin privileges or the IP & Port combination must be allowed by the user executing the application. Alternatively you can use `netsh http add urlacl url=http://+:3070/ user="DOMAIN\User"` (hint there is a user account that denotes everyone). – Nico Jan 15 '14 at 03:10
  • added in the comments of the code. thanks @Nico. Lines 9, 10, 11 – Oxymoron Jan 15 '14 at 03:12
  • @Oxymoron This solution is working really well for me, _however_ I'm having some difficulties modifying things with it... Given the question, this answer is great, my problem is when I'm trying to port forward this page, so that it can be accessed anywhere. Long story short, I am setting up a serial communication protocol using HTTP, for some of my arduino projects. I would like to be able to take whatever serial information, and push it online using this web page. Any ideas...? I tried changing the `const string Prefix = "http://+:3070/";` to my IP address and I'm having no luck. – JesterBaze Jan 15 '14 at 23:53
  • Changing the + symbol to your ip wont do it for you, If you wouldn't mind. Lets start a new question and we'll discuss this issue there. – Oxymoron Jan 16 '14 at 00:29
5

Microsoft Relased an Open Source Project called OWIN it is simlar to Node but bottom line it allows you to host web applications in a console application:

You can find more information here:

But if you insist in creating your personal listener you can find some help here:

Dalorzo
  • 19,834
  • 7
  • 55
  • 102
  • 2
    Every time I see Microsoft and Open Source in one sentence I need to re-read it to be sure. :> – PTwr Jan 15 '14 at 03:07
  • 1
    I am still used to evil M$ shoving cursed IE6 into my face... and look at them now o_O – PTwr Jan 15 '14 at 03:20