如何使用C#Windows窗体创建简单的本地网页

问题描述 投票:5回答:2

我正在使用C#Windows窗体应用程序或C#控制台应用程序创建一个简单的网页。

运行该应用程序将开始在以下位置托管网页:

http://localhost:3070/somepage

我已经在MSDN上阅读了一些有关using endpoints的内容,但是自学成才,这对我来说没有多大意义...

简而言之,该程序在运行时将在localhost:3070的网页上显示一些文本。

很抱歉这样一个模糊的问题,但是我搜索一个体面的教程的时间并没有产生任何可以理解的结果...

感谢您的时间!

c# localhost hosting endpoint
2个回答
6
投票

🛑2020更新:

底部的原始答案。

KestrelKatana现在是一个东西,我强烈建议您以及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();
        }
    }
}

并且要获得额外的信用,请尝试将其添加到计算机上的服务中!


5
投票

Microsoft宣布了一个名为OWIN的开源项目,它与Node类似,但最重要的是,它允许您在控制台应用程序中托管Web应用程序:

© www.soinside.com 2019 - 2024. All rights reserved.