以编程方式在C#中启动HTTP服务器?

我是一个C#,ASP.NET新手。

假设我有一个现有的C#项目(来自“控制台应用程序”模板;我使用Visual Studio)。 我希望能够启动一个简单的HTTP服务器并提供.aspx页面(或普通文本甚至,在这种情况下我也在寻找一个不错的模板库^^),但只有在给程序提供某个命令的情况下通过命令行界面。 (因此,默认情况下服务器不启动。)

我怎么能最好地完成这个?

非常感谢您的帮助!

编辑:为了澄清,我希望所有这些function都嵌入到一个非webapp非网站项目中。 也就是说,该项目由三部分组成:命令行界面,可选运行的Web界面(HTTP服务器),以及通过这两个界面中的任何一个等待并响应请求的核心 。 这是现有项目的当前状态,没有Web界面。

您可以在控制台应用程序中托管ASP.NET运行时。 这是一个例子:

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(); } } } 

运行此程序时可能会收到TypeLoadException 。 您必须为当前目录创建bin子目录,并将可执行文件的副本移动到该子目录。 这是因为ASP.NET运行库将查找bin子目录。 另一个选择是将SimpleHost放入一个单独的程序集中,然后将其部署到GAC中。

这是一篇很好的文章: http : //msdn.microsoft.com/en-us/library/aa529311.aspx

关键是使用Microsoft.Web.Services3

从链接文章复制的示例代码:

 public partial class WindowsServiceToHostASMXWebService : ServiceBase { protected override void OnStart(string[] args) { Uri address = new Uri("soap.tcp://localhost/TestService"); SoapReceivers.Add(new EndpointReference(address), typeof(Service )); } protected override void OnStop() { SoapReceivers.Clear(); } } 

并称之为:

 static void Main() { System.ServiceProcess.ServiceBase[] ServicesToRun; // Change the following line to match. ServicesToRun = new System.ServiceProcess.ServiceBase[] { new WindowsServiceToHostASMXWebService() }; System.ServiceProcess.ServiceBase.Run(ServicesToRun); } 

您可以使用’net’命令启动或停止服务,包括IIS使用的服务(Windows上的Web服务器)。

确保安装了IIS,并且您的站点就像普通的ASP.Net站点一样工作。 然后将“World Wide Web Publishing”服务启动类型设置为手动而不是自动。 现在您可以随时通过在控制台(以及通过Process.Start()从您的程序发出这样的命令)来启动它:

net start w3svc

现在,如果您考虑在任何旧计算机上转储此应用程序,那么您将遇到一些问题。 但如果该应用程序旨在帮助管理特定系统,那么你会没事的。

您可以使用HttpRuntime类。 如果您需要,我可以提供一个简短的演示。