【问题标题】:HttpListenerException "access denied" for non-admins [duplicate]非管理员的HttpListenerException“访问被拒绝”[重复]
【发布时间】: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


【解决方案1】:

我在做 HttpListener 时使用的行是:

netsh http add urlacl url=http://+:8008/ user=Everyone listen=yes

用户可以是个人用户或用户组。因此,如果您希望只有管理员具有访问权限,例如:

netsh http add urlacl url=http://+:8008/ user=Administrators listen=yes

您可以获得有关命令的帮助:

netsh http add urlacl help

请注意,url= 是可选的。此外,旧版本的命令需要 true 或 false 的 listen 参数。当前版本使用是或否。

【讨论】:

  • 好吧,根据此处,用户组并非在所有 Windows 平台上都可用:windows.microsoft.com/en-CA/windows-vista/…。但是,看起来用户=每个人都做到了!!!但是这是在哪里记录的?!!!!我在这上面浪费了 2 天! httpcfg(对于Win XP)有类似的东西吗?谢谢!
  • @user1936026:我不熟悉 httpcfg,但如果我不得不使用它,我可能会从 technet.microsoft.com/en-us/library/cc786389(v=ws.10).aspx 的示例开始
  • 根据帮助,listen 采用 yes|no 值而不是 true|false。 listen=true 对我不起作用。
  • @tafoo85:旧版本的 Windows 使用 true/false。较新的版本使用是/否。或者也许是相反的方式。很高兴您找到了修复程序。
  • @CharlieSalts:据我所知,非管理员不可能成功执行此命令。
猜你喜欢
  • 1970-01-01
  • 2013-04-29
  • 1970-01-01
  • 1970-01-01
  • 2023-03-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-20
相关资源
最近更新 更多