Skip to contentSkip to navigationSkip to topbar
On this page

Workflow Automation with C# and ASP.NET Core


One of the more abstract concepts you'll handle when building your business is what the workflow will look like.

At its core, setting up a standardized workflow is about enabling your service providers (agents, hosts, customer service reps, administrators, and the rest of the gang) to better serve your customers.

To illustrate a very real-world example, today we'll build a C# and ASP.NET Core MVC webapp for finding and booking vacation properties — tentatively called Airtng.

Here's how it'll work:

  1. A host creates a vacation property listing
  2. A guest requests a reservation for a property
  3. The host receives an SMS notifying them of the reservation request. The host can either Accept or Reject the reservation
  4. The guest is notified whether a request was rejected or accepted

Learn how Airbnb used Twilio SMS to streamline the rental experience for 60M+ travelers around the world.(link takes you to an external page)


Workflow Building Blocks

workflow-building-blocks page anchor

We'll be using the Twilio REST API to send our users messages at important junctures. Here's a bit more on our API:

Send messages

send-messages page anchor
1
using System.Threading.Tasks;
2
using AirTNG.Web.Domain.Twilio;
3
using Twilio;
4
using Twilio.Rest.Api.V2010.Account;
5
using Twilio.Types;
6
7
namespace AirTNG.Web.Domain.Reservations
8
{
9
public interface ITwilioMessageSender
10
{
11
Task SendMessageAsync(string to, string body);
12
}
13
14
public class TwilioMessageSender : ITwilioMessageSender
15
{
16
17
private readonly TwilioConfiguration _configuration;
18
19
public TwilioMessageSender(TwilioConfiguration configuration)
20
{
21
_configuration = configuration;
22
23
TwilioClient.Init(_configuration.AccountSid, _configuration.AuthToken);
24
}
25
26
public async Task SendMessageAsync(string to, string body)
27
{
28
await MessageResource.CreateAsync(new PhoneNumber(to),
29
from: new PhoneNumber(_configuration.PhoneNumber),
30
body: body);
31
}
32
}
33
}

Ready to go? Boldly click the button right after this sentence.


For this use case to work we have to handle authentication. We will rely on ASP.NET Core Identity(link takes you to an external page) for this purpose.

Identity User already includes a phone_number that will be required to later send SMS notifications.

1
using System;
2
using Microsoft.AspNetCore.Identity;
3
4
namespace AirTNG.Web.Models
5
{
6
public class ApplicationUser:IdentityUser
7
{
8
9
public string Name { get; set; }
10
11
}
12
}

Next let's take a look at the Vacation Property model.


The Vacation Property Model

the-vacation-property-model page anchor

Our rental application will require listing properties.

The VacationProperty belongs to the User who created it (we'll call this user the host from this point on) and contains only two properties: a Description and an ImageUrl.

A VacationProperty can have many Reservations.

1
using System;
2
using System.Collections.Generic;
3
using System.ComponentModel.DataAnnotations.Schema;
4
using Microsoft.AspNetCore.Identity;
5
6
namespace AirTNG.Web.Models
7
{
8
public class VacationProperty
9
{
10
public int Id { get; set; }
11
public string UserId { get; set; }
12
public string Description { get; set; }
13
public string ImageUrl { get; set; }
14
public DateTime CreatedAt { get; set; }
15
16
[ForeignKey("UserId")]
17
public ApplicationUser User { get; set; }
18
19
public virtual IList<Reservation> Reservations { get; set; }
20
}
21
}

Next, let's see what our Reservation model looks like.


The Reservation model is at the center of the workflow for this application.

It is responsible for keeping track of:

  • The VacationProperty it is associated with to have access. Through this property the user will have access to the host phone number indirectly.
  • The Name and PhoneNumber of the guest.
  • The Message sent to the host on reservation.
  • The Status of the reservation.
1
using System;
2
using System.ComponentModel.DataAnnotations.Schema;
3
4
namespace AirTNG.Web.Models
5
{
6
public class Reservation
7
{
8
public int Id { get; set; }
9
public string Name { get; set; }
10
public string PhoneNumber { get; set; }
11
public ReservationStatus Status { get; set; }
12
public string Message { get; set; }
13
public DateTime CreatedAt { get; set; }
14
public int VacationPropertyId { get; set; }
15
16
[ForeignKey("VacationPropertyId")]
17
public VacationProperty VacationProperty { get; set; }
18
}
19
20
public enum ReservationStatus
21
{
22
Pending = 0,
23
Confirmed = 1,
24
Rejected = 2
25
}
26
}

Now that our models are ready, let's have a look at the controller that will create reservations.


The reservation creation form holds only a single field: the message that will be sent to the host when one of her properties is reserved. The rest of the information needed to create a reservation is taken from the VacationProperty itself.

A reservation is created with a default status ReservationStatus.Pending. That way when the host replies with an accept or reject response the application knows which reservation to update.

The Reservation Controller

the-reservation-controller page anchor
1
using System;
2
using System.Threading.Tasks;
3
using AirTNG.Web.Data;
4
using AirTNG.Web.Domain.Reservations;
5
using Microsoft.AspNetCore.Mvc;
6
using AirTNG.Web.Models;
7
using Microsoft.AspNetCore.Authorization;
8
using Microsoft.AspNetCore.Identity;
9
using Microsoft.Extensions.Logging;
10
11
namespace AirTNG.Web.Tests.Controllers
12
{
13
[Authorize]
14
public class ReservationController : Controller
15
{
16
private readonly IApplicationDbRepository _repository;
17
private readonly IUserRepository _userRepository;
18
private readonly INotifier _notifier;
19
20
public ReservationController(
21
IApplicationDbRepository applicationDbRepository,
22
IUserRepository userRepository,
23
INotifier notifier)
24
{
25
_repository = applicationDbRepository;
26
_userRepository = userRepository;
27
_notifier = notifier;
28
}
29
30
// GET: Reservation/Create/1
31
public async Task<IActionResult> Create(int? id)
32
{
33
if (id == null)
34
{
35
return NotFound();
36
}
37
var property = await _repository.FindVacationPropertyFirstOrDefaultAsync(id);
38
if (property == null)
39
{
40
return NotFound();
41
}
42
43
ViewData["VacationProperty"] = property;
44
return View();
45
}
46
47
// POST: Reservation/Create/1
48
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
49
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
50
[HttpPost]
51
[ValidateAntiForgeryToken]
52
public async Task<IActionResult> Create(int id, [Bind("Message,VacationPropertyId")] Reservation reservation)
53
{
54
if (id != reservation.VacationPropertyId)
55
{
56
return NotFound();
57
}
58
59
if (ModelState.IsValid)
60
{
61
var user = await _userRepository.GetUserAsync(HttpContext.User);
62
reservation.Status = ReservationStatus.Pending;
63
reservation.Name = user.Name;
64
reservation.PhoneNumber = user.PhoneNumber;
65
reservation.CreatedAt = DateTime.Now;
66
67
await _repository.CreateReservationAsync(reservation);
68
var notification = Notification.BuildHostNotification(
69
await _repository.FindReservationWithRelationsAsync(reservation.Id));
70
71
await _notifier.SendNotificationAsync(notification);
72
73
return RedirectToAction("Index", "VacationProperty");
74
}
75
76
ViewData["VacationProperty"] = await _repository.FindVacationPropertyFirstOrDefaultAsync(
77
reservation.VacationPropertyId);
78
return View(reservation);
79
}
80
81
}
82
}

Next, let's see how we will send SMS notifications to the vacation rental host.


When a reservation is created we want to notify the owner of the property that someone is interested.

This is where we use Twilio C# Helper Library(link takes you to an external page) to send a SMS message to the host, using our Twilio phone number(link takes you to an external page). As you can see, sending SMS messages using Twilio takes just a few lines of code.

Next we just have to wait for the host to send an SMS response accepting or rejecting the reservation. Then we can notify the guest and host that the reservation information has been updated.

1
using System;
2
using System.Linq;
3
using System.Text;
4
using System.Threading.Tasks;
5
using AirTNG.Web.Domain.Twilio;
6
using AirTNG.Web.Models;
7
using Twilio;
8
using Twilio.Clients;
9
using Twilio.TwiML.Messaging;
10
11
namespace AirTNG.Web.Domain.Reservations
12
{
13
public interface INotifier
14
{
15
Task SendNotificationAsync(Notification notification);
16
}
17
18
public class Notifier : INotifier
19
{
20
private readonly ITwilioMessageSender _client;
21
22
public Notifier(TwilioConfiguration configuration) : this(
23
new TwilioMessageSender(configuration)
24
) { }
25
26
public Notifier(ITwilioMessageSender client)
27
{
28
_client = client;
29
}
30
31
public async Task SendNotificationAsync(Notification notification)
32
{
33
await _client.SendMessageAsync(notification.To, notification.Message);
34
}
35
}
36
}

Now's let's peek at how we're handling the host's responses.


Handle Incoming Messages

handle-incoming-messages page anchor

The Sms/Handle controller handles our incoming Twilio request and does four things:

  1. Check for the guest's pending reservation
  2. Update the status of the reservation
  3. Respond to the host
  4. Send notification to the guest
1
using System;
2
using System.Collections.Generic;
3
using System.Linq;
4
using System.Threading.Tasks;
5
using AirTNG.Web.Data;
6
using AirTNG.Web.Domain.Reservations;
7
using AirTNG.Web.Models;
8
using Microsoft.AspNetCore.Authorization;
9
using Microsoft.AspNetCore.Mvc;
10
using Microsoft.EntityFrameworkCore;
11
using Twilio.AspNet.Core;
12
using Twilio.TwiML;
13
using Twilio.TwiML.Voice;
14
15
namespace AirTNG.Web.Tests.Controllers
16
{
17
public class SmsController: TwilioController
18
{
19
private readonly IApplicationDbRepository _repository;
20
private readonly INotifier _notifier;
21
22
public SmsController(
23
IApplicationDbRepository repository,
24
INotifier notifier)
25
{
26
_repository = repository;
27
_notifier = notifier;
28
}
29
30
31
// POST Sms/Handle
32
[HttpPost]
33
[AllowAnonymous]
34
public async Task<TwiMLResult> Handle(string from, string body)
35
{
36
string smsResponse;
37
38
try
39
{
40
var host = await _repository.FindUserByPhoneNumberAsync(from);
41
var reservation = await _repository.FindFirstPendingReservationByHostAsync(host.Id);
42
43
var smsRequest = body;
44
reservation.Status =
45
smsRequest.Equals("accept", StringComparison.InvariantCultureIgnoreCase) ||
46
smsRequest.Equals("yes", StringComparison.InvariantCultureIgnoreCase)
47
? ReservationStatus.Confirmed
48
: ReservationStatus.Rejected;
49
50
await _repository.UpdateReservationAsync(reservation);
51
smsResponse = $"You have successfully {reservation.Status} the reservation";
52
53
// Notify guest with host response
54
var notification = Notification.BuildGuestNotification(reservation);
55
56
await _notifier.SendNotificationAsync(notification);
57
}
58
catch (InvalidOperationException)
59
{
60
smsResponse = "Sorry, it looks like you don't have any reservations to respond to.";
61
}
62
catch (Exception)
63
{
64
smsResponse = "Sorry, it looks like we get an error. Try later!";
65
}
66
67
return TwiML(Respond(smsResponse));
68
}
69
70
private static MessagingResponse Respond(string message)
71
{
72
var response = new MessagingResponse();
73
response.Message(message);
74
75
return response;
76
}
77
}
78
}

Let's have closer look at how Twilio webhooks are configured to enable incoming requests to our application.


Incoming Twilio Requests

incoming-twilio-requests page anchor

In the Twilio console(link takes you to an external page), you must setup the SMS webhook to call your application's end point in the route Reservations/Handle.

SMS Webhook.

One way to expose your development machine to the outside world is using ngrok(link takes you to an external page). The URL for the SMS webhook on your number would look like this:

1
http://<subdomain>.ngrok.io/Reservations/Handle
2

An incoming request from Twilio comes with some helpful parameters, such as a from phone number and the message body.

We'll use the from parameter to look for the host and check if they have any pending reservations. If they do, we'll use the message body to check for 'accept' and 'reject'.

In the last step, we'll use Twilio's TwiML as a response to Twilio to send an SMS message to the guest.

Now that we know how to expose a webhook to handle Twilio requests, let's see how we generate the TwiML needed.


After updating the reservation status, we must notify the host that they have successfully confirmed or rejected the reservation. We also have to return a friendly error message if there are no pending reservations.

If the reservation is confirmed or rejected we send an additional SMS to the guest to deliver the news.

We use the verb Message from TwiML to instruct Twilio's server that it should send the SMS messages.

1
using System;
2
using System.Collections.Generic;
3
using System.Linq;
4
using System.Threading.Tasks;
5
using AirTNG.Web.Data;
6
using AirTNG.Web.Domain.Reservations;
7
using AirTNG.Web.Models;
8
using Microsoft.AspNetCore.Authorization;
9
using Microsoft.AspNetCore.Mvc;
10
using Microsoft.EntityFrameworkCore;
11
using Twilio.AspNet.Core;
12
using Twilio.TwiML;
13
using Twilio.TwiML.Voice;
14
15
namespace AirTNG.Web.Tests.Controllers
16
{
17
public class SmsController: TwilioController
18
{
19
private readonly IApplicationDbRepository _repository;
20
private readonly INotifier _notifier;
21
22
public SmsController(
23
IApplicationDbRepository repository,
24
INotifier notifier)
25
{
26
_repository = repository;
27
_notifier = notifier;
28
}
29
30
31
// POST Sms/Handle
32
[HttpPost]
33
[AllowAnonymous]
34
public async Task<TwiMLResult> Handle(string from, string body)
35
{
36
string smsResponse;
37
38
try
39
{
40
var host = await _repository.FindUserByPhoneNumberAsync(from);
41
var reservation = await _repository.FindFirstPendingReservationByHostAsync(host.Id);
42
43
var smsRequest = body;
44
reservation.Status =
45
smsRequest.Equals("accept", StringComparison.InvariantCultureIgnoreCase) ||
46
smsRequest.Equals("yes", StringComparison.InvariantCultureIgnoreCase)
47
? ReservationStatus.Confirmed
48
: ReservationStatus.Rejected;
49
50
await _repository.UpdateReservationAsync(reservation);
51
smsResponse = $"You have successfully {reservation.Status} the reservation";
52
53
// Notify guest with host response
54
var notification = Notification.BuildGuestNotification(reservation);
55
56
await _notifier.SendNotificationAsync(notification);
57
}
58
catch (InvalidOperationException)
59
{
60
smsResponse = "Sorry, it looks like you don't have any reservations to respond to.";
61
}
62
catch (Exception)
63
{
64
smsResponse = "Sorry, it looks like we get an error. Try later!";
65
}
66
67
return TwiML(Respond(smsResponse));
68
}
69
70
private static MessagingResponse Respond(string message)
71
{
72
var response = new MessagingResponse();
73
response.Message(message);
74
75
return response;
76
}
77
}
78
}

Congratulations! You've just learned how to automate your workflow with Twilio SMS.

Next, lets see what else we can do with the Twilio C# SDK.


If you're a .NET developer working with Twilio you know we've got a lot of great content here on the Docs site. Here are just a couple ideas for your next tutorial:

IVR: Phone Tree

You can route callers to the right people and information with an IVR (interactive voice response) system.

Automated Survey

Instantly collect structured data from your users with a survey conducted over a voice call or SMS text messages.

Need some help?

Terms of service

Copyright © 2024 Twilio Inc.