Table of contents

C# resolve HttpListener Access Denied

C# Jun 25, 2020 Viewed 1.6K Comments 0

Issue

In Windows 10, I use HttpListener to listen on port 8081. The code show as below:

try
{
    HttpListener listener = new HttpListener();
    listener.Prefixes.Add("http://*:8081/");
    listener.Start();
} catch(Exception error)
{
    Console.WriteLine(error.Message);
}

An exception occurred after running in Visual Studio 2019.

System.Net.HttpListenerException:"Access Denied"

Solution

Try the following methods.

1. Specify the complete url

Specify the prefix as localhost or 127.0.0.1.

HttpListener listener = new HttpListener();
listener.Prefixes.Add("http://127.0.0.1:8081/");
listener.Start();

2. Configuring namespace reservations

We can run HttpListener in non-admin mode. All we need to do is grant permissions to the particular URL. e.g.

netsh http add urlacl url=http://*:8081/ user=Administrator

Documentation is here.

3. Run as administrator

We can run Visual Studio 2019 as administrator.

Updated Jun 25, 2020