gpt4 book ai didi

c# - 如何在 Windows 服务中托管简单的 ASP.NET Web 界面

转载 作者:太空狗 更新时间:2023-10-29 22:07:40 25 4
gpt4 key购买 nike

对于在 Windows 和 .NET 操作系统上运行的简单设备,我们需要创建一个简单的配置 Web 界面来控制它。就像路由器的配置页面一样,没有比这更复杂的了。

应避免安装 IIS 或任何其他 Web 服务器,我们需要的是在基本 Windows XP 安装 + .NET 上的 Windows 服务中的自支持进程。

单声道兼容性是一个优势。

感谢一百万

最佳答案

实际上,最简单的方法是使用内置的 WCF 工具 (.Net 3.5)...为此,您为“WCF”服务创建一个接口(interface),其中包含一个或多个返回 Stream 的方法:

[ServiceContract]
public interface IService
{
[OperationContract]
[WebInvoke(UriTemplate = "/{*arguments}", Method="GET", BodyStyle=WebMessageBodyStyle.Bare)]
Stream Get(string arguments);
}

您可以定义多个方法和参数并让 WFC 完成工作,或者如上例所示,将所有内容都放入一个方法中。生成的实现可以访问完整的 Uri 和查询参数,如下所示:

public class ServiceType : IService
{
public Stream Get(string arguments)
{
UriTemplateMatch uriInfo = WebOperationContext.Current.IncomingRequest.UriTemplateMatch;
WebOperationContext.Current.OutgoingResponse.ContentType = "text/html";

MemoryStream rawResponse = new MemoryStream();
TextWriter response = new StreamWriter(rawResponse, Encoding.UTF8);
response.Write("<html><head><title>Hello</title></head><body>");
response.Write("<b>Path</b>: {0}<br/>", arguments);
response.Write("<b>RequestUri</b>: {0}<br/>", uriInfo.RequestUri);
response.Write("<b>QueryParameters</b>: {0}<br/>", uriInfo.QueryParameters.ToString());
response.Write("</body></html>");
response.Flush();

rawResponse.Position = 0;
return rawResponse;
}
}

现在您所要做的就是启动 WCF web/http 自托管 ...

static void Main()
{
Uri baseAddress = new Uri("http://localhost:8000/");
WebServiceHost svcHost = new WebServiceHost(typeof(ServiceType));

ServiceEndpoint svcEndpoint = svcHost.AddServiceEndpoint(typeof(IService),
new WebHttpBinding(), baseAddress);
svcEndpoint.Behaviors.Add(new WebHttpBehavior());

svcHost.Open();
Console.WriteLine("Press enter to quit...");
Console.ReadLine();

svcHost.Close();
}

注意:要使上述示例在 Vista/Win7 上运行,您需要使用以下命令行授予权限:

netsh http add urlacl url=http://+:8000/ user=DOMAIN\USER

关于c# - 如何在 Windows 服务中托管简单的 ASP.NET Web 界面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3235865/

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