我正在用c#编写一个HTTP服务器。

当我尝试执行函数HttpListener.Start(),我得到一个HttpListenerException说

“拒绝访问”。

当我在windows 7的管理模式下运行应用程序时,它工作得很好。

我可以让它在没有管理模式的情况下运行吗?如果是,怎么做? 如果不是,我怎么能使应用程序更改为管理模式后开始运行?

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

当前回答

是的,你可以在非管理模式下运行HttpListener。您所需要做的就是将权限授予特定的URL。如。

netsh http add urlacl url=http://+:80/MyUri user=DOMAIN\user

文档在这里。

其他回答

如果你想使用“user=Everyone”标志,你需要根据你的系统语言来调整它。在英语中,如前所述:

netsh http add urlacl url=http://+:80/ user=Everyone

在德语中是:

netsh http add urlacl url=http://+:80/ user=Jeder

如果将应用程序清单添加到项目中,则可以以管理员身份启动应用程序。

只需添加新项目到您的项目,并选择“应用程序清单文件”。将<requestedExecutionLevel>元素更改为:

<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />

语法对我来说是错误的,你必须包括引号:

netsh http add urlacl url="http://+:4200/" user=everyone

否则我收到“参数不正确”

不幸的是,由于某些原因可能链接到HTTPS和证书,本机的.NET HttpListener需要管理权限,甚至仅用于HTTP协议…

好的一点是

值得注意的是,HTTP协议位于TCP协议之上,但启动c# TCP侦听器不需要任何管理权限即可运行。换句话说,实现一个不需要管理特权的HTTP服务器在概念上是可能的。

替代

下面是一个不需要管理权限的项目示例: https://github.com/EmilianoElMariachi/ElMariachi.Http.Server

如果使用http://localhost:80/作为前缀,则可以侦听http请求,而不需要管理权限。