gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 00:24:51 26 4
gpt4 key购买 nike

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

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

http://localhost:3070/somepage

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

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

对于这样一个模糊的问题,我深表歉意,但是我花了几个小时寻找一个像样的教程并没有产生任何可以理解的结果......

感谢您的宝贵时间!

最佳答案

🛑 2020 年更新:

原始答案在底部。

KestrelKatana现在是一件事,我强烈建议您研究这些事情以及 OWIN


原答案:

你会想要研究创建一个HttpListener,你可以给监听器添加前缀,比如Listener.Prefixes.Add("http://+:3070/") 它将把它绑定(bind)到你想要的端口。

一个简单的控制台应用程序:计算发出的请求

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

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

关于c# - 如何使用 C# Windows 窗体创建一个简单的本地网页,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21128218/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com