Search code examples
c#.netnetworkingupnpasp.net-core-5.0

C# - Port Mapping with .Net Core 5.0


Expected Outcome

I'm attempting to make an ASP.NET Core 5.0 application using Kestrel, and I would like to auto port forward the server's port.

Package

I'm currently using the OpenNat.Core package. I have also tried the regular OpenNat and the same issue arises.

Issue

When port forwarding, the program says it has mapped everything correctly and the map even shows when listing all mapped ports on my router. Yet, when I attempt to view its status via CanYouSeeMe.org it returns a timed out error, and I am unable to access the server outside the network.

What I've Tried

  1. I thought that the port mapping might have been opening after the server started, so I manually opened the port and then restarted the Kestrel server.
  2. I made sure that my router supported UPnP
    • I also have a Synology NAS that I port forward from, and it works just fine.
  3. I had a friend use ZenMap to check the port.
    • The port shows that it's filtered but not open (and no service was specified).

Code

using Open.Nat;
using System;
using System.Threading;
using System.Threading.Tasks;
...
        public static async Task OpenPort(int port, string description)
        {
            try
            {
                
                NatDiscoverer discoverer = new NatDiscoverer();
                CancellationTokenSource cts = new CancellationTokenSource(10000);
                NatDevice device = await discoverer.DiscoverDeviceAsync(PortMapper.Upnp, cts);
                Mapping map = new(Protocol.Tcp, port, port, description);
                await device.CreatePortMapAsync(map);
                Console.WriteLine($"Created {map}");
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                Console.WriteLine(e.StackTrace);
            }
        }

Solution

  • Nevermind my firewall was blocking the application. I was able to dynamically add a firewall rule to fix the issue.