Search code examples
.nettemplates

How to generate a random IIS port for a dotnet new custom project template?


When you create a new Web project, it creates a Properties\launchSettings.json file with configuration for IIS like this:

    // ...
    "iisExpress": {
      "applicationUrl": "http://localhost:34390",
      "sslPort": 44333
    }

The port numbers are randomized. This is their source code and there doesn't seem to be anything special:

    "iisExpress": {
      "applicationUrl": "http://localhost:8080",
      //#if (HasHttpsProfile)
      "sslPort": 44300
      //#else
      "sslPort": 0
      //#endif
    }

I am making a custom web template but I am stumbling at this. How do I generate a random port number like them?


Solution

  • Found the source code for it, turned out I was looking at the wrong place. The static number there is replaced by a declaration in the template.json, not in that file or the .csproj file:

            "iisHttpsPortGenerated": {
                "type": "generated",
                "generator": "port",
                "parameters": {
                    "low": 44300,
                    "high": 44399
                }
            },
            "iisHttpsPortReplacer": {
                "type": "generated",
                "generator": "coalesce",
                "parameters": {
                    "sourceVariableName": "iisHttpsPort",
                    "fallbackVariableName": "iisHttpsPortGenerated"
                },
                "replaces": "44300"
            }
    

    It uses .NET templating random symbol in case it's helpful for anyone.