Heroku is a great tool to host personal projects and there's a free tier. However, .Net Core is not supported for now but, there's a work around this.
Prerequisites
- A Heroku account - https://signup.heroku.com/
- Install the Heroku CLI - https://devcenter.heroku.com/articles/heroku-cli
- git enabled
Create a new app on the Heroku website
and ensure the app name is unique.-
Open the terminal on your system, change directory to your core project and log into Heroku account.
heroku login
-
Add the Heroku Git remote
heroku git:remote -a {your app name}
-
We need a dotnet buildpack because, dotnet is not supported.
For this tutorial, I used and my .net core version is 3.1.3 https://elements.heroku.com/buildpacks/jincod/dotnetcore-buildpackUse this command if your .net core version is the same as mine
heroku buildpacks:set https://github.com/jincod/dotnetcore-buildpack\#v3.1.3
If you are on a .net 5. You can use this command
heroku buildpacks:set jincod/dotnetcore
Ensure you are on heroku-18 stack
heroku stack:set heroku-18
To a database resource: Navigate to the resources tab then search for ClearDB MySql and select the free version.
To get the connection string, you need to navigate to the settings and click on Reveal Config Vars.
Also, add ASPNETCORE_ENVIRONMENT config and set it to Production.
ClearDb connection string is usually in this format :
mysql://username:password@host/databasename?reconnect=true
you can use the code snippet below to build the connection string for EF core
services.AddDbContext<DbContext>(x =>
{
var env = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
string connStr;
if (env == "Development")
{
connStr = Configuration.GetConnectionString("DemoConnection");
}
else
{
// Use connection string provided at runtime by Heroku.
var connUrl = Environment.GetEnvironmentVariable("CLEARDB_DATABASE_URL");
connUrl = connUrl.Replace("mysql://", string.Empty);
var userPassSide = connUrl.Split("@")[0];
var hostSide = connUrl.Split("@")[1];
var connUser = userPassSide.Split(":")[0];
var connPass = userPassSide.Split(":")[1];
var connHost = hostSide.Split("/")[0];
var connDb = hostSide.Split("/")[1].Split("?")[0];
connStr = $"server={connHost};Uid={connUser};Pwd={connPass};Database={connDb}";
}
x.UseMySql(connStr);
});
Now we are set to publish to heroku. Use the command below to achieve this
git push heroku master
Once publishing has been completed, your app url can be found in the settings tab.
Top comments (2)
Thank you for sharing! This tutorial is straight to the point and does not have a lot of dependencies like other tutorials. Just the good and old Git, .NET ecosystem and Heroku. It worked like a charm!
Glad it was easy to follow