Domanda

Sto scrivendo un server HTTP in C#.

Quando provo a eseguire la funzione HttpListener.Start() Ottengo un HttpListenerException detto

"Accesso negato".

Quando eseguo l'app in modalità amministratore in Windows 7 funziona bene.

Posso farlo funzionare senza modalità amministratore? Se sì come? In caso contrario, come posso far cambiare l'app in modalità amministratore dopo aver iniziato a funzionare?

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;
                }
            }
        }
    }
}
È stato utile?

Soluzione

Sì, puoi eseguire HttplStener in modalità non addmin. Tutto quello che devi fare è concedere le autorizzazioni al particolare URL. per esempio

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

La documentazione è qui.

Altri suggerimenti

Posso farlo funzionare senza modalità amministratore? Se sì come? In caso contrario, come posso far cambiare l'app in modalità amministratore dopo aver iniziato a funzionare?

Non puoi, deve iniziare con privilegi elevati. Puoi riavviarlo con il runas Verbo, che spingerà l'utente a passare alla modalità amministratore

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

EDIT: In realtà, non è vero; Httplistener può essere eseguito senza privilegi elevati, ma è necessario dare il permesso all'URL su cui si desidera ascoltare. Vedere La risposta di Darrel Miller per dettagli.

Se usi http://localhost:80/ Come prefisso, puoi ascoltare le richieste HTTP senza necessità di privilegi amministrativi.

La sintassi era sbagliata per me, devi includere le citazioni:

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

Altrimenti ho ricevuto "il parametro non è corretto"

Nel caso in cui desideri utilizzare il flag "utente = tutti" devi regolarlo al linguaggio del sistema. In inglese è come menzionato:

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

In tedesco sarebbe:

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

In alternativa che non richiede elevazione o neth, è anche possibile utilizzare TCplStener per esempio.

Quello che segue è un estratto modificato di questo campione: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

I metodi di lettura e scrittura sono:

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

Puoi avviare l'applicazione come amministratore se aggiungi manifest dell'applicazione al tuo progetto.

Basta aggiungere un nuovo elemento al tuo progetto e selezionare "File manifest dell'applicazione". Cambiare il <requestedExecutionLevel> elemento a:

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

Per impostazione predefinita Windows definisce il seguente prefisso disponibile per tutti:http: //+: 80/temporary_listen_addresses/

Quindi puoi registrare il tuo HttpListener attraverso:

Prefixes.Add("http://+:80/Temporary_Listen_Addresses/" + Guid.NewGuid().ToString("D") + "/";

Questo a volte provoca problemi con software come Skype che proveranno a utilizzare la porta 80 per impostazione predefinita.

httpListener.Prefixes.Add("http://*:4444/");

Usi "*" in modo da eseguire seguenti CMD come amministratore

netsh http add urlacl url=http://*:4444/ user=username

Nessun uso +, deve usare *, perché si specifica *: 4444 ~.

https://msdn.microsoft.com/en-us/library/system.net.httplistener.aspx

Ho anche affrontato un problema simile. Se hai già riservato l'URL, quindi devi prima eliminare l'URL per eseguire in modalità non amministratore, altrimenti, non riuscirà a non riuscire a essere negato l'errore.

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

Netsh richiede diritti di amministrazione

Puoi risolverlo per LocalHost senza diritti di amministrazione impostando IGNOREWITEEXCEPTIONS:

listener.IgnoreWriteExceptions = True
listener.Start()
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top