【发布时间】:2013-02-04 10:05:11
【问题描述】:
我编写了一个 C# 应用程序,它使用 HttpListener 来监听 HTTP 请求 - 很明显!我使用的命名空间前缀也是使用 netsh 为当前用户注册的(正如 SO 上的每个人所建议的那样)。
问题是尽管使用了 netsh,但我的应用程序仍然会为非管理员用户抛出“访问被拒绝”异常。操作系统是 Windows 7。
更新:当我使用非管理员用户运行我的应用程序时,它似乎没有执行netsh 命令。我的代码有问题吗?没有抛出异常。
AddAddress("http://localhost:8400/", Environment.UserDomainName, Environment.UserName);
HttpListener _listener = new HttpListener();
_listener.Prefixes.Add("http://localhost:8400/");
_listener.Start();
...
/** method stolen from an SO thread. sorry can't remember the author **/
static void AddAddress(string address, string domain, string user)
{
string args = string.Format(@"http add urlacl url={0}", address) + " user=\"" + domain + "\\" + user + "\"";
ProcessStartInfo psi = new ProcessStartInfo("netsh", args);
psi.Verb = "runas";
psi.CreateNoWindow = true;
psi.WindowStyle = ProcessWindowStyle.Hidden;
psi.UseShellExecute = true;
Process.Start(psi).WaitForExit();
}
【问题讨论】:
-
这可能是由于 Windows 7 不允许用户模式应用程序在端口 80(这是 HTTP 的默认设置)上创建侦听器。看到这个答案:stackoverflow.com/a/4115328/507793
-
谢谢。我没有使用端口 80。我也刚刚发布了我的代码。
-
我怀疑您的
netsh未能添加您想要的映射。或者可能是因为您使用的是locolhast而不是localhost。或者这只是你的问题中的一个错字? -
SO 编辑器不允许我输入 localhost,所以我不得不更改它!此外,当我在命令提示符下运行相同的 netsh 命令时,我会收到一条消息,指出名称空间已注册。所以我认为 netsh 是成功的。
-
在命令提示符下输入
netsh http show urlacl,然后找到您输入的条目。确保“听”为“是”。我记得,您必须在用户名后添加“listen=true”。
标签: c# exception httplistener non-admin