2010-01-01 19 views
6

Win 7 e VS2010 B2. Sto cercando di scrivere un server web minimale usando il built-in HttpListener. Tuttavia, continuo a ricevere un'eccezione AccessDenied. Ecco il codice:Perché viene visualizzato "AccessDenied" quando si tenta di utilizzare HttpListener?

int Run(string[] args) { 

     _server = new HttpListener(); 
     _server.Prefixes.Add("http://*:9669/"); 
     _server.Start(); 

     Console.WriteLine("Server bound to: {0}", _server.Prefixes.First()); 

     _server.BeginGetContext(HandleContext, null); 
    } 

ho potuto capire la necessità di eseguire come amministratore se ero vincolanti per una porta di sistema, ma non vedo il motivo per cui il mio legame al 9669 dovrebbe richiedere permessi speciali.

Qualche idea?

risposta

23

Grazie a questa domanda SO: Can I listen on a port (using HttpListener or other .NET code) on Vista without requiring administrator priveleges?

ho una risposta.

netsh http add urlacl url=http://*:9669/ user=fak listen=yes

Pazzo. Ecco la mia funzione rivista:

int Run(string[] args) { 

     var prefix = "http://*:9669/"; 
     var username = Environment.GetEnvironmentVariable("USERNAME"); 
     var userdomain = Environment.GetEnvironmentVariable("USERDOMAIN"); 

     _server = new HttpListener(); 
     _server.Prefixes.Add(prefix); 

     try { 
      _server.Start(); 
     } 
     catch (HttpListenerException ex) { 
      if (ex.ErrorCode == 5) { 
       Console.WriteLine("You need to run the following command:"); 
       Console.WriteLine(" netsh http add urlacl url={0} user={1}\\{2} listen=yes", 
        prefix, userdomain, username); 
       return -1; 
      } 
      else { 
       throw; 
      } 
     } 


     Console.WriteLine("Server bound to: {0}", _server.Prefixes.First()); 

     _server.BeginGetContext(HandleContext, null); 
    } 
+1

più sicurezza per tutti noi per imparare –

+0

Sembra che tu abbia davvero bisogno di 'listen = yes'. Ha funzionato per me senza di essa. Inoltre, ho usato 'http: // +: 9669 /'. –

Problemi correlati