I had the same error message when trying to generate visual studio project files/compile from an old UE4 project into UE5.
This fixed it for me:
In visual studio I had already installed Dotnet runtime 3.1, but in CMD the “dotnet” command was not recognized. So I went to the link @anonymous_user_6a2fb347 posted and reinstalled dotnet 3.1. Now it shows correctly in CMD and I no longer get the error.