Skip to main content

Part 2: Route Activities with AgentApplication

Your agent receives many kinds of activities, and each one needs the right code: help should get the help text, a new member a welcome, a reaction a thank-you. AgentApplication makes that decision for every activity with routes. In this part you build a help desk agent with six routes, watch which one answers each activity, and read the order the SDK tries them in, straight from its own log.

This is Part 2 of the Microsoft 365 Agents SDK Fundamentals, a 26-part series.

  1. Part 1: Activities and the Activity Protocol
  2. Part 2: Route Activities with AgentApplication (you are here)
  3. Part 3: Turn Events, Error Handling and Middleware
  4. Part 4: Conversation, User and Turn State
  5. Part 5: Send Adaptive Cards and Handle Their Actions
  6. Part 6: Send Proactive Messages (coming soon)
  7. Part 7: Stream Responses and Show Progress (coming soon)
  8. Part 8: Run Your Agent in Microsoft Teams (coming soon)
  9. Part 9: Universal Actions: Adaptive Cards That Update (coming soon)
  10. Part 10: Teams Dialogs (coming soon)
  11. Part 11: Commands, Suggested Actions and Targeted Messages (coming soon)
  12. Part 12: Mentions, Rosters and Team Events (coming soon)
  13. Part 13: Meeting Events (coming soon)
  14. Part 14: Send and Receive Files (coming soon)
  15. Part 15: Sign People In with SSO and OAuth (coming soon)
  16. Part 16: Message Extensions and Link Unfurling (coming soon)
  17. Part 17: AI Labels, Citations and Feedback (coming soon)
  18. Part 18: Bring Your Agent to Microsoft 365 Copilot (coming soon)
  19. Part 19: Store State in Azure Blob Storage and Cosmos DB (coming soon)
  20. Part 20: Telemetry with OpenTelemetry (coming soon)
  21. Part 21: Web Chat and Direct Line (coming soon)
  22. Part 22: Reach People in Slack (coming soon)
  23. Part 23: Call a Copilot Studio Agent (coming soon)
  24. Part 24: Agent-to-Agent Communication (coming soon)
  25. Part 25: Keep Conversation Transcripts (coming soon)
  26. Part 26: Deploy Your Agent to Azure (coming soon)

By the end of this part you'll know what a route is, which route methods the SDK offers and what exactly each one matches, the order routes are tried in and how to change it, and how to let more than one route handle the same activity. You'll also know how to see your agent's route order in its log, which is the fastest way to find out why the wrong handler answered. Every step works in VS Code and in Visual Studio; where they differ, the page shows a tab for each. Every output and screenshot on this page is real.

What a Route Is​

A route is a pair: a selector, a function that looks at the incoming activity and answers yes, I want this one or no, and a handler, the method that runs when the answer is yes. Your agent's constructor registers its routes, and AgentApplication keeps them in a list.

When an activity arrives, the SDK walks that list in order and asks each route's selector. The first route that says yes runs its handler, and routing for that activity is over. If no route says yes, nothing runs: the activity was accepted, and nobody answers it.

The non-terminal branch is the exception to first match wins: a route marked non-terminal runs its handler and lets the routes after it be tried too. You'll use one in this part.

The Route Methods​

You rarely write selectors yourself. AgentApplication has a method for each common case, and each one builds the selector for you:

MethodMatchesExample
OnMessage("help", ...)A message whose whole text is help, ignoring casehelp, HELP; not help me
OnMessage(new Regex(...), ...)A message whose text matches a regular expressionticket 1234
OnActivity(ActivityTypes.Message, ...)Every activity of a typeevery message
OnConversationUpdate(ConversationUpdateEvents.MembersAdded, ...)A conversationUpdate that adds at least one member; MembersRemoved for members leavingsomeone joining
OnEvent("themeChanged", ...)An event activity with that name, ignoring casea signal from a web page
OnMessageReactionsAdded(...), OnMessageReactionsRemoved(...)A messageReaction that adds or removes reactionsa like
AddRoute(...) with a route builderWhatever your own selector function says, with every optionanything you can check in code

Later parts add more, such as routes for Adaptive Card actions. Each On... method is a shortcut: it builds the route with one of the SDK's route builders, such as MessageRouteBuilder, and adds it with AddRoute. You use a builder yourself when you need an option the shortcut doesn't have, as you will here.

The Order Routes Are Tried In​

The list isn't kept in the order you register routes. The SDK sorts it when each route is added, by three rules:

  1. Invoke routes come first. An invoke activity waits for its answer in the response to its own request, as Part 1 explained, so its routes are tried before all others. Routes for agentic requests from Microsoft Agent 365 get groups of their own too; this part doesn't use them.
  2. Then by rank. Every route has a number from 0 to 65535, and lower numbers are tried first.
  3. Equal ranks keep the order you registered them in.

You set the rank with a rank argument or the builders' WithOrderRank, using the RouteRank constants:

ConstantValueUse it for
RouteRank.First0A route that must be tried before all others
RouteRank.Unspecified32767Everything else; the default when you give no rank
RouteRank.Last65535A catch-all, tried only after every other route

Most routes keep the default. The rank matters for routes that overlap: a catch-all that takes every message must come after the routes for specific messages, and this part shows what happens when it doesn't.

The Example: A Help Desk Agent​

To see routes at work, you'll build a small help desk agent with six routes, one for each kind of rule:

WhenThe agentRoute
Someone joins the conversationWelcomes themConversation update
You send helpLists what it understandsExact text
You send ticket 1234Reads the ticket number from your messageRegular expression
You react to one of its messagesSays thanksReactions
Your message mentions urgentFlags it, and lets another route answer tooYour own selector, ranked first, non-terminal
You send anything elseLogs it as a new requestCatch-all, ranked last

It has no AI and no ticket system, so the routes are the only new thing on the page. You'll run it in the Microsoft 365 Agents Playground, as in Part 1.

Prerequisites​

  • The .NET 10 SDK. dotnet --version should print 10.0. and a patch number; this page was built with 10.0.404.
  • The Microsoft 365 Agents Playground. agentsplayground --version should print 0.2.30. If the command isn't found, install it with npm install -g @microsoft/m365agentsplayground.
  • What an activity is, from Part 1: Activities and the Activity Protocol.

Step 1: Create the Project​

Open a terminal in the folder where you keep your projects and create an empty ASP.NET Core project, as in Part 1:

Terminal
dotnet new web -o HelpDesk
Output
The template "ASP.NET Core Empty" was created successfully.

Processing post-creation actions...
Restoring /Users/you/source/HelpDesk/HelpDesk.csproj:
Restore succeeded.

Then add the Agents SDK's hosting package, which brings the rest of the SDK with it:

Terminal
cd HelpDesk
dotnet add package Microsoft.Agents.Hosting.AspNetCore --version 1.9.205
Output (last lines)
info : PackageReference for package 'Microsoft.Agents.Hosting.AspNetCore' version '1.9.205' added to file '/Users/you/source/HelpDesk/HelpDesk.csproj'.
info : Generating MSBuild file /Users/you/source/HelpDesk/obj/HelpDesk.csproj.nuget.g.targets.
info : Writing assets file to disk. Path: /Users/you/source/HelpDesk/obj/project.assets.json
log : Restored /Users/you/source/HelpDesk/HelpDesk.csproj (in 926 ms).

Step 2: Write the Help Desk Agent​

Create a file called HelpDeskAgent.cs in the project folder. You'll write the routes first, then their handlers, then see the whole file.

The Routes​

The constructor registers all six routes:

HelpDeskAgent.cs (the class and its routes)
using System.Text.RegularExpressions;
using Microsoft.Agents.Builder;
using Microsoft.Agents.Builder.App;
using Microsoft.Agents.Builder.State;
using Microsoft.Agents.Core.Models;

namespace HelpDesk;

public class HelpDeskAgent : AgentApplication
{
// "ticket", one or more spaces, then a number of up to six digits, in any capitalization.
private static readonly Regex TicketPattern = new(@"^ticket\s+(\d{1,6})$", RegexOptions.IgnoreCase);

public HelpDeskAgent(AgentApplicationOptions options) : base(options)
{
// New members in the conversation: welcome them.
OnConversationUpdate(ConversationUpdateEvents.MembersAdded, WelcomeAsync);

// The message "help", in any capitalization.
OnMessage("help", HelpAsync);

// A message such as "ticket 1234".
OnMessage(TicketPattern, TicketAsync);

// Someone reacted to one of the agent's messages.
OnMessageReactionsAdded(ReactionAsync);

// Any message that mentions "urgent": tried first, and the other routes still run after it.
AddRoute(MessageRouteBuilder.Create()
.WithSelector(MentionsUrgentAsync)
.WithHandler(FlagUrgentAsync)
.WithOrderRank(RouteRank.First)
.AsNonTerminal()
.Build());

// Every other message: tried last, so it gets only what the routes above don't take.
OnActivity(ActivityTypes.Message, NewRequestAsync, rank: RouteRank.Last);
}
  • OnConversationUpdate(ConversationUpdateEvents.MembersAdded, WelcomeAsync) matches a conversationUpdate activity with at least one member in MembersAdded.
  • OnMessage("help", HelpAsync) matches a message whose whole text is help, in any capitalization. It doesn't look for the word inside a longer message.
  • OnMessage(TicketPattern, TicketAsync) matches a message whose text fits the regular expression. ^ and $ pin the pattern to the start and end of the text, \s+ is one or more spaces, (\d{1,6}) captures a number of up to six digits, and RegexOptions.IgnoreCase accepts Ticket and TICKET as well. The pattern is static readonly, so it's built once, not on every message.
  • OnMessageReactionsAdded(ReactionAsync) matches a messageReaction activity that adds at least one reaction.
  • The urgent route uses a route builder, because it needs two options the shortcuts don't have. MessageRouteBuilder builds routes for messages only. .WithSelector(MentionsUrgentAsync) gives it your own selector function, .WithOrderRank(RouteRank.First) puts it before all other routes, and .AsNonTerminal() lets the routes after it be tried too. .Build() returns the route, and AddRoute registers it.
  • OnActivity(ActivityTypes.Message, NewRequestAsync, rank: RouteRank.Last) matches every message, but with the last rank, so it gets only the messages no other route took.

The routes are registered in this order, but the urgent route will be tried first and the catch-all last: the ranks decide, as Step 5 shows.

The Handlers​

Each handler has the same signature you met in Part 1: the turn's context, its state and a cancellation token.

HelpDeskAgent.cs (the handlers)
private async Task WelcomeAsync(ITurnContext turnContext, ITurnState turnState, CancellationToken cancellationToken)
{
foreach (ChannelAccount member in turnContext.Activity.MembersAdded)
{
// The agent is one of the members added; don't welcome it.
if (member.Id != turnContext.Activity.Recipient.Id)
{
await turnContext.SendActivityAsync("Hi! I'm the help desk agent. Type **help** to see what I can do.", cancellationToken: cancellationToken);
}
}
}

private async Task HelpAsync(ITurnContext turnContext, ITurnState turnState, CancellationToken cancellationToken)
{
await turnContext.SendActivityAsync(
"Here's what I understand:\n\n" +
"- **help**: this list\n" +
"- **ticket** and a number, such as **ticket 1234**: ask about a ticket\n" +
"- anything else: a new request for the help desk",
cancellationToken: cancellationToken);
}

private async Task TicketAsync(ITurnContext turnContext, ITurnState turnState, CancellationToken cancellationToken)
{
// The route matched, so the pattern matches: read the number from its first group.
string ticketNumber = TicketPattern.Match(turnContext.Activity.Text).Groups[1].Value;
await turnContext.SendActivityAsync($"You asked about ticket **{ticketNumber}**. A real help desk would look it up now.", cancellationToken: cancellationToken);
}

private async Task ReactionAsync(ITurnContext turnContext, ITurnState turnState, CancellationToken cancellationToken)
{
string reactions = string.Join(", ", turnContext.Activity.ReactionsAdded.Select(reaction => reaction.Type));
await turnContext.SendActivityAsync($"Thanks for the {reactions}!", cancellationToken: cancellationToken);
}

// The selector of the urgent route: true when the message's text contains "urgent", in any capitalization.
private static Task<bool> MentionsUrgentAsync(ITurnContext turnContext, CancellationToken cancellationToken)
{
bool mentionsUrgent = turnContext.Activity.Text?.Contains("urgent", StringComparison.OrdinalIgnoreCase) == true;
return Task.FromResult(mentionsUrgent);
}

private async Task FlagUrgentAsync(ITurnContext turnContext, ITurnState turnState, CancellationToken cancellationToken)
{
await turnContext.SendActivityAsync("I've marked this as **urgent**.", cancellationToken: cancellationToken);
}

private async Task NewRequestAsync(ITurnContext turnContext, ITurnState turnState, CancellationToken cancellationToken)
{
await turnContext.SendActivityAsync($"Thanks, I've logged a new request: \"{turnContext.Activity.Text}\"", cancellationToken: cancellationToken);
}
}
  • WelcomeAsync loops over MembersAdded, because one update can add several people. The agent itself is one of the members added, so it skips the member whose Id is the agent's own, Recipient.Id.
  • TicketAsync runs the pattern again to read the number. Groups[1] is the part inside the first pair of brackets, (\d{1,6}).
  • MentionsUrgentAsync is a selector: it gets the turn's context and returns true or false, wrapped in a Task because selectors may be asynchronous. It has no ITurnState, because it only decides; the handler does the work. MessageRouteBuilder already checks that the activity is a message, so the selector only looks at the text. ?. and == true handle a message with no text.

TicketAsync and MentionsUrgentAsync are the only places that read the message text in code. The routing itself is all in the constructor.

The Complete File​

HelpDeskAgent.cs
using System.Text.RegularExpressions;
using Microsoft.Agents.Builder;
using Microsoft.Agents.Builder.App;
using Microsoft.Agents.Builder.State;
using Microsoft.Agents.Core.Models;

namespace HelpDesk;

public class HelpDeskAgent : AgentApplication
{
// "ticket", one or more spaces, then a number of up to six digits, in any capitalization.
private static readonly Regex TicketPattern = new(@"^ticket\s+(\d{1,6})$", RegexOptions.IgnoreCase);

public HelpDeskAgent(AgentApplicationOptions options) : base(options)
{
// New members in the conversation: welcome them.
OnConversationUpdate(ConversationUpdateEvents.MembersAdded, WelcomeAsync);

// The message "help", in any capitalization.
OnMessage("help", HelpAsync);

// A message such as "ticket 1234".
OnMessage(TicketPattern, TicketAsync);

// Someone reacted to one of the agent's messages.
OnMessageReactionsAdded(ReactionAsync);

// Any message that mentions "urgent": tried first, and the other routes still run after it.
AddRoute(MessageRouteBuilder.Create()
.WithSelector(MentionsUrgentAsync)
.WithHandler(FlagUrgentAsync)
.WithOrderRank(RouteRank.First)
.AsNonTerminal()
.Build());

// Every other message: tried last, so it gets only what the routes above don't take.
OnActivity(ActivityTypes.Message, NewRequestAsync, rank: RouteRank.Last);
}

private async Task WelcomeAsync(ITurnContext turnContext, ITurnState turnState, CancellationToken cancellationToken)
{
foreach (ChannelAccount member in turnContext.Activity.MembersAdded)
{
// The agent is one of the members added; don't welcome it.
if (member.Id != turnContext.Activity.Recipient.Id)
{
await turnContext.SendActivityAsync("Hi! I'm the help desk agent. Type **help** to see what I can do.", cancellationToken: cancellationToken);
}
}
}

private async Task HelpAsync(ITurnContext turnContext, ITurnState turnState, CancellationToken cancellationToken)
{
await turnContext.SendActivityAsync(
"Here's what I understand:\n\n" +
"- **help**: this list\n" +
"- **ticket** and a number, such as **ticket 1234**: ask about a ticket\n" +
"- anything else: a new request for the help desk",
cancellationToken: cancellationToken);
}

private async Task TicketAsync(ITurnContext turnContext, ITurnState turnState, CancellationToken cancellationToken)
{
// The route matched, so the pattern matches: read the number from its first group.
string ticketNumber = TicketPattern.Match(turnContext.Activity.Text).Groups[1].Value;
await turnContext.SendActivityAsync($"You asked about ticket **{ticketNumber}**. A real help desk would look it up now.", cancellationToken: cancellationToken);
}

private async Task ReactionAsync(ITurnContext turnContext, ITurnState turnState, CancellationToken cancellationToken)
{
string reactions = string.Join(", ", turnContext.Activity.ReactionsAdded.Select(reaction => reaction.Type));
await turnContext.SendActivityAsync($"Thanks for the {reactions}!", cancellationToken: cancellationToken);
}

// The selector of the urgent route: true when the message's text contains "urgent", in any capitalization.
private static Task<bool> MentionsUrgentAsync(ITurnContext turnContext, CancellationToken cancellationToken)
{
bool mentionsUrgent = turnContext.Activity.Text?.Contains("urgent", StringComparison.OrdinalIgnoreCase) == true;
return Task.FromResult(mentionsUrgent);
}

private async Task FlagUrgentAsync(ITurnContext turnContext, ITurnState turnState, CancellationToken cancellationToken)
{
await turnContext.SendActivityAsync("I've marked this as **urgent**.", cancellationToken: cancellationToken);
}

private async Task NewRequestAsync(ITurnContext turnContext, ITurnState turnState, CancellationToken cancellationToken)
{
await turnContext.SendActivityAsync($"Thanks, I've logged a new request: \"{turnContext.Activity.Text}\"", cancellationToken: cancellationToken);
}
}

HelpDeskAgent.cs in a macOS-style editor window: the class, a static Regex for ticket numbers, and a constructor that registers six routes: OnConversationUpdate for members added, OnMessage for help, OnMessage with the ticket pattern, OnMessageReactionsAdded, an urgent route built with MessageRouteBuilder using its own selector, RouteRank.First and AsNonTerminal, and a catch-all OnActivity for messages with RouteRank.Last

Step 3: Host and Run the Agent​

Replace everything in Program.cs with the same hosting Part 1 uses, with HelpDeskAgent as the agent:

Program.cs
using HelpDesk;
using Microsoft.Agents.Hosting.AspNetCore;
using Microsoft.Agents.Storage;

var builder = WebApplication.CreateBuilder(args);

builder.AddAgentDefaults()
.AddAgent<HelpDeskAgent>();
builder.Services.AddSingleton<IStorage, MemoryStorage>();

var app = builder.Build();

app.UseAgents();
app.MapDefaultAgentEndpoints();

app.Run();

Then open Properties/launchSettings.json and set the two applicationUrl lines to port 3978, where the Agents Playground looks by default:

Properties/launchSettings.json (the two lines to change)
"applicationUrl": "http://localhost:3978",
Properties/launchSettings.json (in the https profile)
"applicationUrl": "https://localhost:3979;http://localhost:3978",

Build it:

Terminal
dotnet build
Output
Restore complete (0.3s)
HelpDesk net10.0 succeeded (1.4s) → bin/Debug/net10.0/HelpDesk.dll

Build succeeded in 2.3s

And start it:

In the terminal, in the project folder:

Terminal
dotnet run
Output
Using launch settings from /Users/you/source/HelpDesk/Properties/launchSettings.json...
Building...
warn: Microsoft.Agents.Authentication.ConfigurationConnections[0]
No connections found in configuration.
warn: Microsoft.Agents.Authentication.ConfigurationConnections[0]
No connections map found in configuration.
info: Microsoft.Agents.Hosting.AspNetCore.BackgroundQueue.HostedActivityService[0]
Queued Hosted Service is running.
info: Microsoft.Agents.Hosting.AspNetCore.BackgroundQueue.HostedTaskService[0]
Queued Hosted Service is running.

info: Microsoft.Hosting.Lifetime[14]
Now listening on: http://localhost:3978
info: Microsoft.Hosting.Lifetime[0]
Application started. Press Ctrl+C to shut down.
info: Microsoft.Hosting.Lifetime[0]
Hosting environment: Development
info: Microsoft.Hosting.Lifetime[0]
Content root path: /Users/you/source/HelpDesk

The two warnings mean the agent has no identity of its own yet, which the Playground doesn't need. Leave the agent running.

Step 4: Watch Each Route Answer​

Open a second terminal and start the Agents Playground as the emulator channel:

Terminal 2
agentsplayground -e http://localhost:3978/api/messages -c emulator

The Playground connects and sends a conversationUpdate that adds you and the agent. The members-added route takes it, skips the agent, and welcomes you:

The agent Test Bot's first message in the Agents Playground: Hi! I'm the help desk agent. Type help to see what I can do., with help in bold

Exact Text​

Send help, then HELP, then help me:

The Playground chat: the messages help and HELP each get the agent's list Here's what I understand, with help, ticket and a number, and anything else; the message help me gets Thanks, I've logged a new request: "help me"

help and HELP both reached the help route: it compares the whole text and ignores case. help me didn't, because its text isn't exactly help, so it fell through to the catch-all.

A Regular Expression​

Send ticket 1234, then ticket abc:

The Playground chat: ticket 1234 gets You asked about ticket 1234. A real help desk would look it up now., with 1234 in bold; ticket abc gets Thanks, I've logged a new request: "ticket abc"

The pattern matched ticket 1234, and the handler read 1234 from the pattern's group. abc isn't a number, so ticket abc matched nothing but the catch-all.

A Non-Terminal Route​

Send Urgent: my laptop won't start. You get two answers:

The Playground chat: the message Urgent: my laptop won't start gets two replies, I've marked this as urgent., then Thanks, I've logged a new request: "Urgent: my laptop won't start"

The urgent route was tried first and its selector said yes, so its handler flagged the message. Because the route is non-terminal, the SDK went on down the list: help and ticket didn't match, and the catch-all logged the request. Without .AsNonTerminal(), the flag would have been the only answer.

A Reaction​

A reaction isn't something you type. Send one from the Playground the way Part 1 did: copy the id of the agent's latest reply from the Response tab of its message 201 line in the Log Panel, choose Mock an Activity → Custom activity, and replace the "type": "<custom-activity-type>" line with these three, using your own id (the whole procedure is in How to Send a Custom Activity from the Microsoft 365 Agents Playground):

Custom activity (replace the type line)
"type": "messageReaction",
"reactionsAdded": [{ "type": "like" }],
"replyToId": "1795243744918"

Select Send activity. The reaction route answers:

The Playground chat: the agent's reply Thanks, I've logged a new request: "Urgent: my laptop won't start", followed by its answer to the reaction, Thanks for the like!

Every kind of activity found its route. Next, you'll see the list the SDK walked to find them.

Step 5: See the Order the SDK Tries Your Routes In​

AgentApplication writes its sorted route list to the log on every turn, just before it tries the routes, at the Debug level. ASP.NET Core only shows Information and above by default, so turn on Debug for the SDK's routing code. Replace appsettings.Development.json with this:

appsettings.Development.json
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning",
"Microsoft.Agents.Builder.App": "Debug"
}
}
}

Microsoft.Agents.Builder.App is the namespace of AgentApplication and its routes, so only their Debug messages are turned on; everything else stays as it was. dotnet run uses the Development environment, which is why this file applies. Stop the agent with Ctrl+C, start it again with dotnet run, and send help in the Playground. The agent's terminal now shows the list before the turn's other lines:

Terminal (the agent, the start of the turn)
warn: Microsoft.Agents.Hosting.AspNetCore.CloudAdapter[4]
Anonymous access is enabled for channel: emulator.
dbug: Microsoft.Agents.Builder.App.AgentApplication[1]
AgentApplication route evaluation order (6 routes): [{"Index":0,"Handler":"HelpDeskAgent.FlagUrgentAsync","Flags":"NonTerminal","Rank":0,"Channel":"*"},{"Index":1,"Handler":"HelpDeskAgent.WelcomeAsync","Flags":"None","Rank":32767,"Channel":"*"},{"Index":2,"Handler":"HelpDeskAgent.HelpAsync","Flags":"None","Rank":32767,"Channel":"*"},{"Index":3,"Handler":"HelpDeskAgent.TicketAsync","Flags":"None","Rank":32767,"Channel":"*"},{"Index":4,"Handler":"HelpDeskAgent.ReactionAsync","Flags":"None","Rank":32767,"Channel":"*"},{"Index":5,"Handler":"HelpDeskAgent.NewRequestAsync","Flags":"None","Rank":65535,"Channel":"*"}]

The list is one line of JSON. Laid out as a table:

IndexHandlerFlagsRank
0FlagUrgentAsyncNonTerminal0
1WelcomeAsyncNone32767
2HelpAsyncNone32767
3TicketAsyncNone32767
4ReactionAsyncNone32767
5NewRequestAsyncNone65535

That's exactly the order the routes were tried in Step 4. The urgent route was registered fifth but comes first, because of its rank 0. The four routes with the default rank keep the order the constructor registered them in. The catch-all comes last because of its rank 65535. Channel is * for routes that match activities from every channel.

The warning above the list is logged for every activity that arrives without authentication, which is how an agent with no identity runs on your machine. Part 8, which runs the agent in Teams, gives it one.

Step 6: Send an Activity No Route Matches​

None of the six routes handles event activities. Open Mock an Activity → Custom activity again and replace the type line with an event:

Custom activity (replace the type line)
"type": "event",
"name": "pageOpened"

Select Send activity. Nothing comes back, and the Log Panel shows why it's not an error:

The end of the Playground's Log Panel: message 202 help and its message 201 reply, then event 202 sent to the agent, with no reply after it

The agent accepted the event with 202, as it accepts every activity, and sent nothing. Its terminal says so:

Terminal (the agent)
dbug: Microsoft.Agents.Builder.App.AgentApplication[2]
No route matched for ActivityType=event

That line, again at the Debug level, is the first thing to look for when your agent stays silent: it means the activity arrived, but no route wanted it.

Step 7: See What Happens Without RouteRank.Last​

The catch-all's rank is what keeps it from swallowing everything. To see that, move its line to the top of the constructor and remove the rank:

HelpDeskAgent.cs (the start of the constructor, changed)
public HelpDeskAgent(AgentApplicationOptions options) : base(options)
{
// The catch-all, registered first and without a rank.
OnActivity(ActivityTypes.Message, NewRequestAsync);

Restart the agent with dotnet run and send help:

The Playground chat: the message help now gets Thanks, I've logged a new request: "help" instead of the help list

The route list shows why:

Terminal (the agent)
dbug: Microsoft.Agents.Builder.App.AgentApplication[1]
AgentApplication route evaluation order (6 routes): [{"Index":0,"Handler":"HelpDeskAgent.FlagUrgentAsync","Flags":"NonTerminal","Rank":0,"Channel":"*"},{"Index":1,"Handler":"HelpDeskAgent.NewRequestAsync","Flags":"None","Rank":32767,"Channel":"*"},{"Index":2,"Handler":"HelpDeskAgent.WelcomeAsync","Flags":"None","Rank":32767,"Channel":"*"},{"Index":3,"Handler":"HelpDeskAgent.HelpAsync","Flags":"None","Rank":32767,"Channel":"*"},{"Index":4,"Handler":"HelpDeskAgent.TicketAsync","Flags":"None","Rank":32767,"Channel":"*"},{"Index":5,"Handler":"HelpDeskAgent.ReactionAsync","Flags":"None","Rank":32767,"Channel":"*"}]

Without a rank, the catch-all has the default 32767, like the help route, and it was registered first, so it's tried first. Its selector says yes to every message, and routing stops there: the help route never gets asked. Put the line back where it was, with rank: RouteRank.Last, and restart the agent before you go on.

Step 8: Register Routes with Attributes​

The constructor isn't the only place to register routes. The SDK also has route attributes: you put one on the handler method, and the SDK registers the route for you. These three attributes do the same as three lines of the constructor, which you'd remove:

HelpDeskAgent.cs (three handlers with route attributes)
[MembersAddedRoute]
private async Task WelcomeAsync(ITurnContext turnContext, ITurnState turnState, CancellationToken cancellationToken)
{
// ... the same body as before
}

[MessageRoute("help")]
private async Task HelpAsync(ITurnContext turnContext, ITurnState turnState, CancellationToken cancellationToken)
{
// ... the same body as before
}

[MessageReactionsAddedRoute]
private async Task ReactionAsync(ITurnContext turnContext, ITurnState turnState, CancellationToken cancellationToken)
{
// ... the same body as before
}

Only the attribute line above each method is new. With these three attributes, and the OnConversationUpdate, OnMessage("help", ...) and OnMessageReactionsAdded lines removed from the constructor, help and ticket 42 get the same answers as before, but the route list changes:

Terminal (the agent)
dbug: Microsoft.Agents.Builder.App.AgentApplication[1]
AgentApplication route evaluation order (6 routes): [{"Index":0,"Handler":"HelpDeskAgent.FlagUrgentAsync","Flags":"NonTerminal","Rank":0,"Channel":"*"},{"Index":1,"Handler":"HelpDeskAgent.WelcomeAsync","Flags":"None","Rank":32767,"Channel":"*"},{"Index":2,"Handler":"HelpDeskAgent.HelpAsync","Flags":"None","Rank":32767,"Channel":"*"},{"Index":3,"Handler":"HelpDeskAgent.ReactionAsync","Flags":"None","Rank":32767,"Channel":"*"},{"Index":4,"Handler":"HelpDeskAgent.TicketAsync","Flags":"None","Rank":32767,"Channel":"*"},{"Index":5,"Handler":"HelpDeskAgent.NewRequestAsync","Flags":"None","Rank":65535,"Channel":"*"}]

The reaction route now comes before the ticket route, although the constructor used to register it after. The SDK adds attribute routes when AgentApplication's own constructor runs, which is before the code in yours. So with equal ranks, attribute routes are tried before constructor routes, in the order the methods appear in the class. Here that changes nothing, because the two routes never match the same activity; with overlapping routes, give them ranks.

Use whichever style you prefer, and keep one agent to one style where you can, so its order is easy to read. The rest of this course registers routes in the constructor. Every attribute, and the pitfall in their regular expressions, is in How to Define Routes with Attributes in the Microsoft 365 Agents SDK in C#.

Stop and Clean Up​

Press Ctrl+C in both terminals, or use Debug → Stop Debugging (Shift+F5) in Visual Studio. This part created nothing outside your project folder, and nothing in the cloud. The Playground wrote its log to a devTools folder in the folder you started it from; delete it whenever you like. When you've finished with the agent, delete the HelpDesk folder.

What You Can Do Now​

  • Register routes for exact text, regular expressions, activity types, conversation updates, events and reactions.
  • Write your own selector function and register it with a route builder.
  • Predict the order routes are tried in from their kind, their rank and the order you registered them.
  • Add a catch-all that only gets what other routes don't take.
  • Let more than one route handle an activity with AsNonTerminal().
  • Turn on the SDK's Debug log to see your agent's route list, and recognize No route matched when an activity goes unanswered.
  • Register routes with attributes, and know where they land in the order.

Common Mistakes​

MistakeWhat happensDo this instead
A catch-all without RouteRank.LastRegistered before the specific routes, it answers every messageGive every catch-all rank: RouteRank.Last
Expecting OnMessage("help", ...) to match help meOnly the whole text help matches, ignoring caseUse a regular expression for anything longer
A regular expression without ^ and $new Regex("ticket") also matches my ticket is latePin the pattern to the start and end of the text
Welcoming every member in MembersAddedThe agent welcomes itselfSkip the member whose Id equals Recipient.Id
Expecting every matching route to runOnly the first matching route runsMark the earlier route .AsNonTerminal()
Mixing attribute and constructor routes with the same rankAttribute routes are tried first, whatever order the code suggestsGive overlapping routes explicit ranks

Troubleshooting​

SymptomLikely causeFix
The catch-all answers a message that has its own routeThe catch-all comes earlier in the route listTurn on the Debug log, check the list, and give the catch-all RouteRank.Last
No answer, and the Log Panel shows 202No route matched the activityLook for No route matched for ActivityType=... in the Debug log, then add a route for that type
Only the urgent answer comes backThe urgent route isn't marked non-terminalAdd .AsNonTerminal() to its builder
The route list doesn't appearDebug isn't on for Microsoft.Agents.Builder.App, or the app isn't in the Development environmentCheck appsettings.Development.json and the Hosting environment line at startup
error CS0104: 'RouteBuilder' is an ambiguous referenceYou used the general RouteBuilder in a web projectAdd the using RouteBuilder = ...; alias, or use a typed builder such as MessageRouteBuilder

FAQ​

IntelliSense says OnMessage's text is a "substring". Which is it?​

The whole text. The method's documentation comment calls the parameter a substring, but the SDK compares the complete message text with it, ignoring case, as Microsoft Learn's AgentApplication page says and Step 4 showed: help me didn't match help.

Will help still match in a Teams channel, where people @mention the agent?​

The SDK is built for it: before routing a message, it removes the mention of your agent from the text, an option called RemoveRecipientMention that is on by default. Part 12 shows mentions in real Teams.

Where do invoke activities go?​

To invoke routes, which are tried before all others because the sender is waiting for the answer. Part 9, on Universal Actions, and Part 10, on Teams dialogs, handle the first ones.

Can a route match activities from one channel only?​

Yes. Route builders have a WithChannelId option, and the route list's Channel column shows the channel each route is limited to; * means every channel.

Should the Debug log stay on in production?​

No. It writes the route list for every activity. Turn it on while you work out a routing problem, and back off afterwards; appsettings.Development.json only applies in the Development environment anyway.

Conclusion​

A route is a selector and a handler. AgentApplication tries your routes in a fixed order, invoke routes first, then by rank, then in the order you registered them, and runs the first one whose selector says yes, unless that route is non-terminal. The On... methods cover the common cases, route builders give you every option, and attributes are a second way to register the same routes. When the wrong handler answers, or none does, the Debug log shows you the list the SDK walked.

Next: Part 3: Turn Events, Error Handling and Middleware. Routes decide which handler runs; Part 3 covers the code that runs around every handler, before and after each turn and when something goes wrong.

Additional Resources​