我正在用C#编写一个超文本传输协议服务器。
当我尝试执行函数HttpListener.Start()
时,我得到一个HttpListenerException
,说
“拒绝访问”。
当我在windows7的管理模式下运行这个应用程序时,它工作得很好。
我可以让它在没有管理模式的情况下运行吗?如果是,是如何实现的?如果没有,我如何使应用程序在开始运行后更改为管理模式?
using System;
using System.Net;
namespace ConsoleApplication1
{
class Program
{
private HttpListener httpListener = null;
static void Main(string[] args)
{
Program p = new Program();
p.Server();
}
public void Server()
{
this.httpListener = new HttpListener();
if (httpListener.IsListening)
throw new InvalidOperationException("Server is currently running.");
httpListener.Prefixes.Clear();
httpListener.Prefixes.Add("http://*:4444/");
try
{
httpListener.Start(); //Throws Exception
}
catch (HttpListenerException ex)
{
if (ex.Message.Contains("Access is denied"))
{
return;
}
else
{
throw;
}
}
}
}
}
发布于 2010-11-07 05:44:59
是的,您可以在非管理模式下运行HttpListener。您所需要做的就是授予特定URL的权限。例如:
netsh http add urlacl url=http://+:80/MyUri user=DOMAIN\user
文档是here。
发布于 2010-10-26 07:26:39
我可以让它在没有管理模式的情况下运行吗?如果是,是如何实现的?如果没有,我如何使应用程序在开始运行后更改为管理模式?
你不能,它必须从提升的特权开始。您可以使用runas
谓词重新启动它,这将提示用户切换到管理模式
static void RestartAsAdmin()
{
var startInfo = new ProcessStartInfo("yourApp.exe") { Verb = "runas" };
Process.Start(startInfo);
Environment.Exit(0);
}
EDIT:实际上,这不是真的;HttpListener可以在没有提升权限的情况下运行,但是您需要为您想要监听的URL提供权限。详情请参见Darrel Miller's answer。
发布于 2013-09-13 20:35:29
如果使用http://localhost:80/
作为前缀,则可以在不需要管理权限的情况下侦听http请求。
https://stackoverflow.com/questions/4019466
复制相似问题