HttpListener Access Denied
I am writing an HTTP server in C#.
When I try to execute the function HttpListener.Start()
I get an HttpListenerException
saying
"Access Denied".
When I run the app in admin mode in windows 7 it works fine.
Can I make it run without admin mode? if yes how? If not how can I make the app change to admin mode after start running?
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;
}
}
}
}
}
Yes you can run HttpListener in non-admin mode. All you need to do is grant permissions to the particular URL. e.g.
netsh http add urlacl url=http://+:80/MyUri user=DOMAIN\user
Documentation is here.
Can I make it run without admin mode? if yes how? If not how can I make the app change to admin mode after start running?
You can't, it has to start with elevated privileges. You can restart it with the runas
verb, which will prompt the user to switch to admin mode
static void RestartAsAdmin()
{
var startInfo = new ProcessStartInfo("yourApp.exe") { Verb = "runas" };
Process.Start(startInfo);
Environment.Exit(0);
}
EDIT: actually, that's not true; HttpListener can run without elevated privileges, but you need to give permission for the URL on which you want to listen. See Darrel Miller's answer for details.