我正在用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;
                }
            }
        }
    }
}

当前回答

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

你不能,必须从更高的特权开始。您可以使用runas谓词重新启动它,这将提示用户切换到管理模式

static void RestartAsAdmin()
{
    var startInfo = new ProcessStartInfo("yourApp.exe") { Verb = "runas" };
    Process.Start(startInfo);
    Environment.Exit(0);
}

编辑:事实上,这不是真的;HttpListener可以在没有提升权限的情况下运行,但是您需要为希望侦听的URL授予权限。详见达雷尔·米勒的回答。

其他回答

我也遇到过类似的问题。如果你已经保留了url,那么你必须首先删除url以非管理模式运行,否则它将失败,访问是拒绝错误。

netsh http delete urlacl url=http://+:80

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

作为一个不需要提升或netsh的替代方案,你也可以使用TcpListener。

以下是经过修改的摘录: https://github.com/googlesamples/oauth-apps-for-windows/tree/master/OAuthDesktopApp

// Generates state and PKCE values.
string state = randomDataBase64url(32);
string code_verifier = randomDataBase64url(32);
string code_challenge = base64urlencodeNoPadding(sha256(code_verifier));
const string code_challenge_method = "S256";

// Creates a redirect URI using an available port on the loopback address.
var listener = new TcpListener(IPAddress.Loopback, 0);
listener.Start();
string redirectURI = string.Format("http://{0}:{1}/", IPAddress.Loopback, ((IPEndPoint)listener.LocalEndpoint).Port);
output("redirect URI: " + redirectURI);

// Creates the OAuth 2.0 authorization request.
string authorizationRequest = string.Format("{0}?response_type=code&scope=openid%20profile&redirect_uri={1}&client_id={2}&state={3}&code_challenge={4}&code_challenge_method={5}",
    authorizationEndpoint,
    System.Uri.EscapeDataString(redirectURI),
    clientID,
    state,
    code_challenge,
    code_challenge_method);

// Opens request in the browser.
System.Diagnostics.Process.Start(authorizationRequest);

// Waits for the OAuth authorization response.
var client = await listener.AcceptTcpClientAsync();

// Read response.
var response = ReadString(client);

// Brings this app back to the foreground.
this.Activate();

// Sends an HTTP response to the browser.
WriteStringAsync(client, "<html><head><meta http-equiv='refresh' content='10;url=https://google.com'></head><body>Please close this window and return to the app.</body></html>").ContinueWith(t =>
{
    client.Dispose();
    listener.Stop();

    Console.WriteLine("HTTP server stopped.");
});

// TODO: Check the response here to get the authorization code and verify the code challenge

读取和写入方法为:

private string ReadString(TcpClient client)
{
    var readBuffer = new byte[client.ReceiveBufferSize];
    string fullServerReply = null;

    using (var inStream = new MemoryStream())
    {
        var stream = client.GetStream();

        while (stream.DataAvailable)
        {
            var numberOfBytesRead = stream.Read(readBuffer, 0, readBuffer.Length);
            if (numberOfBytesRead <= 0)
                break;

            inStream.Write(readBuffer, 0, numberOfBytesRead);
        }

        fullServerReply = Encoding.UTF8.GetString(inStream.ToArray());
    }

    return fullServerReply;
}

private Task WriteStringAsync(TcpClient client, string str)
{
    return Task.Run(() =>
    {
        using (var writer = new StreamWriter(client.GetStream(), new UTF8Encoding(false)))
        {
            writer.Write("HTTP/1.0 200 OK");
            writer.Write(Environment.NewLine);
            writer.Write("Content-Type: text/html; charset=UTF-8");
            writer.Write(Environment.NewLine);
            writer.Write("Content-Length: " + str.Length);
            writer.Write(Environment.NewLine);
            writer.Write(Environment.NewLine);
            writer.Write(str);
        }
    });
}

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

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

在德语中是:

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

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

好的一点是

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

替代

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