Luke Warren Dev
Software Development Tips and Stories When I feel Like It

How to configure the Hangfire Dashboard in an ASP.NET App

Hangfire is an awesome little library to aid in the scheduling of recurring or deferred "jobs".

,
Categories: C# , ASP.NET
Tags: Hangfire , ASP.NET , MVC , C#

Hangfire is an awesome little library to aid in the scheduling of recurring or deferred "jobs".

It comes with a handy dashboard that, when configured, allows you to easily monitor and take actions on your jobs.

The problem I have come across on StackOverflow and other sites is that many people battle to get the dashboard setup, so I thought that I would document here how it is done.

First we need to create an authorization filter

This will be used later to make sure that only authenticated and authorised users can access the dashboard.

This means making sure that users are both logged in and in the admin role before they can view the Hangfire dashboard.

using MyApp.Common;
using Hangfire.Dashboard;
using Microsoft.Owin;
using System.Collections.Generic;

namespace MyApp.Dashboard.Schedules
{
   public class HangfireAuthorizationFilter : IAuthorizationFilter
   {
          public HangfireAuthorizationFilter()
          {
          }

          public bool Authorize(IDictionary<string, object> owinEnvironment)
          {
             // Only admin users can access the dashboard
             var user = new OwinContext(owinEnvironment).Authentication.User;
             return user.Identity.IsAuthenticated &amp;&amp; user.IsInRole(RoleKeys.Admin);
          }
      }
}

All you need to do really is implement the IAuthorizationFilter interface and you are away.

Next, we need to configure our app to use the Hangfire dashboard

I usually just create a static method that sets up the dashboard and adds whatever jobs I need run.

We are using the authorization filter created previously.

public static class ScheduleConfig
{
    public static void ConfigureSchedules(IAppBuilder app)
    {
        // Configure Dashboard
        GlobalConfiguration.Configuration.UseSqlServerStorage("DefaultConnection");
        // I like to use "/jobs" as my endpoint
        // but your could change that to whatever you like
        app.UseHangfireDashboard("/jobs", new DashboardOptions
        {
            AuthorizationFilters = new[] { new HangfireAuthorizationFilter() }
        });
        app.UseHangfireServer();

        // Add jobs
        //...
    }
}

All we need to do now is call our method from within Startup.cs

public partial class Startup
{
    public void Configuration(IAppBuilder app)
    {
        // Other startup config
        //...

        // Call our method to configure hangfire.
        ScheduleConfig.ConfigureSchedules(app);
    }
}

Now (once logged in as admin) you will be able to navigate to the dashboard via http://yourappdomain.com/jobs


comments powered by Disqus