Instant errors on SMS from ASP.NET Core with Twilio and elmah.io

This post was originally published on the Twilio blog: https://www.twilio.com/blog/real-time-sms-error-messages-asp-net-core-elmah-io

Getting instant notifications when an error happens on a website can mean life and death for a business. The faster developers fix the bug, the fewer users get frustrated with your website. Using elmah.io and Twilio, getting SMS notifications when your ASP.NET Core application starts failing requires nothing more than a few lines of code. In this post, you will learn how.

You can receive elmah.io alerts through a variety of channels, including Slack and Microsoft Teams, using integrations provided for those and other products. You can also receive alerts by SMS using the elmah.io integration for Twilio. With a Twilio Phone Number you can receive text notifications about your website wherever you have cellular coverage.

This post will show you how to register for elmah.io, configure the Twilio integration, and add elmah.io to an ASP.NET Core MVC application. When you’re done you’ll be receiving error notifications on your own mobile phone.

Prerequisites

To build the project described in this post you’ll need the following tools:

  • Visual Studio 2017/2019, Visual Studio Code, or an IDE or editor of your choice
  • ASP.NET Core 2.2 (The SDK download includes the runtime.)

To get the most out of this post you should have some familiarity with C#, ASP.NET Core, and the MVC design pattern, but extensive programming experience is not required.

Setting up elmah.io

To sign up for a free elmal.io trial, go to the signup page and input a username and password, or pick one of the social providers:

Elmah.io sign up page

When signed up, add the requested pieces of information on the update user screen:

Update user screen on elmah.io

Finally, input your company name on the Create organization screen:

Create organization screen

A new account is now created on elmah.io and you are ready to start integrating. On the next screen, you will see your API key and Log ID. Copy them to a safe place. It’s important you don’t share your API key with anyone outside your organization.

The API key is a token sent to all endpoints on the elmah.io API. The Log ID is the ID of the error log to send errors to. You can create individual error logs per application, customer, team, or whatever way you prefer.

Keep your elmah.io tab open. You’ll be using it later.

Integrating elmah.io with ASP.NET Core

To integrate elmah.io, start by creating a new ASP.NET Core MVC project called “AspNetCore.ElmahIo.Example”. This will give you a basic set of views and a controller you can modify to demonstrate the elmah.io error logging.

If you’re using Visual Studio Code or another editor you can create the project from a console window. Be sure you have the .NET SDK installed first. Execute the following command line instruction in the directory where you’d like to create the project directory:

dotnet new mvc -lang C# --name AspNetCore.ElmahIo.Example

You can also create the project by using the Visual Studio 2017/2019 user interface to create an ASP.NET Core 2.2 Web Application with the MVC template.

Next, install the Elmah.Io.AspNetCore NuGet package using one of these options or the Visual Studio 2017/2019 user interface:

.NET CLI

dotnet add package Elmah.Io.AspNetCore

Package Manager Console (for Visual Studio 2017/2019)

Install-Package Elmah.Io.AspNetCore

In the project root directory, open the Startup.cs file and replace the contents with the following C# code:

using System;
using Elmah.Io.AspNetCore;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

namespace AspNetCore.ElmahIo.Example
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<CookiePolicyOptions>(options =>
            {
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            services.AddElmahIo(options =>
            {
                options.ApiKey = "API_KEY";
                options.LogId = new Guid("LOG_ID");
            });

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
        }

        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseElmahIo();

            app.UseStaticFiles();
            app.UseCookiePolicy();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
}

The example is based on the default template when creating a new ASP.NET Core 2.2 MVC project through Visual Studio 2017/2019 or the .NET CLI. Adding elmah.io requires few modifications. Here are the changes one by one:

Locate the following code in the ConfigureService method. You’ll see that the AddElmahIo method sets a couple of options.

Replace the API_KEY AND LOG_ID placeholders with the values you saved when you set up your elmah.io account.

services.AddElmahIo(options =>
{
    options.ApiKey = "API_KEY";
    options.LogId = new Guid("LOG_ID");
});

Note: This is unsafe. Be sure not to share this code in a publicly accessible source code repository. In production code you should store private data using the user secrets manager or environment variables.

In the Configure method the following call to UseElmahIo has been added:

app.UseElmahIo();

It’s important to call this method after using other pieces of middleware that handle exceptions (like UseDeveloperExceptionPage and UseExceptionHandler) but before the UseMvc call. ASP.NET Core middleware works like pearls on a string, where one middleware component calls the next, which calls the next, and so on. Some middleware implements may “swallow” all exceptions, making errors inaccessible for other middleware components.

Testing elmah.io error logging in ASP.NET Core

Error logging is now configured and all errors are sent to elmah.io. To test that the integration works, add a test exception to one of the controllers.

In the Controllers folder, open the HomeController.cs file and modify the Index() method by replacing return View() with an exception, as shown below:

using System;
using System.Diagnostics;
using Elmah.Io.AspNetCore;
using Microsoft.AspNetCore.Mvc;
using AspNetCore.ElmahIo.Example.Models;

namespace AspNetCore.ElmahIo.Example.Controllers
{
    public class HomeController : Controller
    {
        public IActionResult Index()
        {
            throw new Exception("Look ma, I’m a failing controller!");
        }

        public IActionResult Privacy()
        {
            return View();
        }
    }
}

You want to remove the throw new Exception part before deploying your code to production, but it serves well for a quick test.

Start the application. If you’re running in debug mode and your development environment is set to break on unhandled exceptions it will stop on the throw line. Continue running the application. The test exception should appear in the browser window.

Navigate to your elmah.io log. The exception is shown in the error log configured:

Elmah.io error log configuration

To avoid having to check the error log constantly, you should set up one or more integrations and/or notifications. elmah.io supports a range of different apps and integrations through the elmah.io App Store. Examples of integrations include:

  • Create a bug in Jira when new errors are logged.
  • Notify the team on Slack or Microsoft Teams on new errors.
  • Notify elmah.io Deployment Tracking when publishing new versions on Azure DevOps.

Setting up SMS notifications through a Twilio phone number

For this post the focus is on SMS text messages. elmah.io supports this through integration with Twilio.

To sign up for Twilio, navigate to https://www.twilio.com/try-twilio in your browser. Follow the guided process for creating a free trial account and selecting a Twilio phone number.

During the process you’ll be asked to register a phone number. Use your mobile phone number or another number capable of receiving SMS messages. It’s important you have access to the phone you register because Twilio trial accounts are only able to send messages to registered phones.

After signing up for Twilio you have access to the three key pieces of information you need to set up the integration:

  • Trial Number
  • Account SID
  • Auth Token

The dashboard where you can find this information is shown below:

Twilio Console

The Account SID, and Auth Token are user secrets, so follow the same precautions as for the elmah.io secrets.

On elmah.io, navigate to the log settings screen by clicking onto the gears icon next to the log. On the Apps tab, at the top of the page, there’s a Twilio app near the bottom:

Elmah.io apps tab

After clicking Install, enter your Twilio trial number in the From box, your registered (mobile) phone number in the To box, the Account SID in the Account SID box, and the Auth Token in the Account Token box. The user interface looks like the following:

Elmah.io UI

Finally, click the Save button. The integration with Twilio is successfully configured.

Testing SMS error notifications with Twilio

To test the integration, a new exception should be thrown. elmah.io triggers most integrations on new errors only, to avoid spamming your mailbox or sending you millions of text messages.

Change the exception type and message in the HomeController class to ensure elmah.io captures the exception as a new error:

using System;
using System.Diagnostics;
using Elmah.Io.AspNetCore;
using Microsoft.AspNetCore.Mvc;
using AspNetCore.ElmahIo.Example.Models;

namespace AspNetCore.ElmahIo.Example.Controllers
{
    public class HomeController : Controller
    {
        public IActionResult Index()
        {
            throw new NullReferenceException($"Null at {DateTime.UtcNow.Ticks}!");
        }

        public IActionResult Privacy()
        {
            return View();
        }
    }
}

For this example, you’re generating unique exception messages using a date to ensure elmah.io fires SMS messages for all instances. This approach should only be used for testing the Twilio integration, since it would quickly use up your message quota in a production application.

When launching the project, a text message is sent to the configured phone number:

Text message to phone number

There you go. As soon as your ASP.NET Core website starts failing you will receive instant notifications on your phone.

Summary

This post explained how to set up SMS text messages through Twilio when an ASP.NET Core website throws errors. Both elmah.io and Twilio offer free trial accounts so you can work with the tools in development before making a financial commitment.

Additional resources

More information about elmah.io can be found at https://elmah.io.

More information about Twilio can be found at https://www.twilio.com.

The Twilio integration for elmah.io is on the documentation site: Install Twilio for elmah.io.

Features steps
We monitor your websites

We monitor your websites

We monitor your websites for crashes and availability. This helps you get an overview of the quality of your applications and to spot trends in your releases.

We notify you

We notify you

We notify you when errors starts happening using Slack, HipChat, mail or other forms of communication to help you react to errors before your users do.

We help you fix bugs

We help you fix bugs

We help you fix bugs quickly by combining error diagnostic information with innovative quick fixes and answers from Stack Overflow and social media.

See how we can help you monitor your website for crashes Monitor your website