Programmatically starting an HTTP server in C#?

前端 未结 4 846
不思量自难忘°
不思量自难忘° 2021-02-01 11:20

I\'m a C#, ASP.NET newbie.

Let\'s say I have an existing C# project (from a \"Console Application\" template; I work with Visual Studio). I want to be able to start a si

4条回答
  •  说谎
    说谎 (楼主)
    2021-02-01 11:52

    You could host the ASP.NET runtime inside a console application. Here's an example:

    public class SimpleHost : MarshalByRefObject
    {
        public void ProcessRequest(string page, string query, TextWriter writer)
        {
            SimpleWorkerRequest swr = new SimpleWorkerRequest(page, query, writer);
            HttpRuntime.ProcessRequest(swr);
        }
    }
    
    class Program
    {
        static void Main(string[] args)
        {
            // TODO: Check to see if a given argument has been passed on the command-line
    
            SimpleHost host = (SimpleHost)ApplicationHost.CreateApplicationHost(
                typeof(SimpleHost), "/", Directory.GetCurrentDirectory());
    
            HttpListener listener = new HttpListener();
            listener.Prefixes.Add("http://localhost:9999/");
            listener.Start();
            Console.WriteLine("Listening for requests on http://localhost:9999/");
    
            while (true)
            {
                HttpListenerContext context = listener.GetContext();
                string page = context.Request.Url.LocalPath.Replace("/", "");
                string query = context.Request.Url.Query.Replace("?", "");
                using (var writer = new StreamWriter(context.Response.OutputStream))
                {
                    host.ProcessRequest(page, query, writer);
                }
                context.Response.Close();
            }
    
        }
    }
    

    You might get a TypeLoadException when you run this program. You have to create a bin subdirectory to your current directory and move a copy of the executable to it. This is because the ASP.NET runtime will look for a bin subdirectory. Another option is to put SimpleHost into a separate assembly which you deploy into the GAC.

提交回复
热议问题