我希望创建一个简单的网页,使用 C# Windows Forms 应用程序或 C# 控制台应用程序。
运行应用程序将开始在以下位置托管网页:
http://localhost:3070/somepage
我已经在MSDN上了解了一些有关使用端点的内容,但由于自学,这对我来说并不是很清楚...简单来说,当程序运行时,它将在localhost:3070上的网页上显示一些文本。很抱歉问题描述得比较含糊,但我搜索了几个小时也没有找到一个理解起来容易的教程...感谢您的时间!
我希望创建一个简单的网页,使用 C# Windows Forms 应用程序或 C# 控制台应用程序。
运行应用程序将开始在以下位置托管网页:
http://localhost:3070/somepage
原始答案在底部。
Kestrel和Katana现在也是一件事情,我强烈建议您研究这些东西以及OWIN
您需要研究创建HttpListener
,您可以向侦听器添加前缀,例如Listener.Prefixes.Add("http://+:3070/")
,这将将其绑定到您想要的端口。
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();
}
}
}
netsh http add urlacl url=http://+:3070/ user="DOMAIN\User"
(提示:有一个用户帐户表示所有人)。 - Nicoconst string Prefix = "http://+:3070/";
更改为我的IP地址,但没有成功。 - JesterBaze微软发布了一个名为OWIN的开源项目,类似于Node,但底线是它允许您在控制台应用程序中托管Web应用程序:
您可以在此处找到更多信息:
但是如果您坚持创建自己的监听器,您可以在这里找到一些帮助:
HttpListener
: http://msdn.microsoft.com/zh-cn/library/system.net.httplistener(v=vs.110).aspx - Simon WhiteheadHttpListener
的原因..)。 - Simon Whitehead