Skip to main content

Part 11: Show a Web Page in a Teams Dialog

Part 10's dialogs showed Adaptive Cards, which your agent builds from text, inputs and buttons. Some tasks need more than a card can draw: a room's seat map, a picture to mark up, a page you already have. For those, a Microsoft Teams dialog can show a web page of your own, and the page sends its result to your agent, the same way a card's button does.

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

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

By the end of this part you'll know how a dialog shows a web page, what Teams needs from the page and from your app, and how the page talks to Teams and to your agent. You'll build a seat-booking agent whose dialog shows a room's seats, books the one you pick, and shows the page again with a message when someone else got there first.

How a Dialog Shows a Web Page​

In Part 10, the agent answered task/fetch with continue and a card. For a web page, the answer is still continue, with a url in place of the card. Microsoft's Invoke and dismiss dialogs describes url as the URL of the page loaded as an <iframe> inside the dialog. An iframe is a web page shown inside another web page: here, your page inside Teams.

Teams loads the page in the person's own Teams client, from your server, so the page and your app have a few things to get right:

Teams needsWhat Microsoft's docs sayIn this part
An HTTPS addressEach url and fallbackUrl must implement the HTTPS encryption protocol. (Use dialogs with bots)The dev tunnel's https:// address
The page's domain in the app's manifestThe URL's domain must be in the app's validDomains array in your app manifest. (Invoke and dismiss dialogs)Step 8
Teams among the sites the page lets frame itA table of the frame-ancestors values that allow Teams and the other Microsoft 365 apps. (Requirements for tabs)Steps 5 and 7
The Teams JavaScript library, connectedAfter your page loads, make a call to app.initialize(). (Requirements for tabs)Step 4

The Teams JavaScript library, TeamsJS, is how the page talks to Teams. This part uses three of its calls:

CallWhat it does
microsoftTeams.app.initialize()Connects the page to Teams. Its reference says it must have completed successfully (as determined by the resolved Promise) before any other library calls are made.
microsoftTeams.app.getContext()Tells the page where it runs, Teams' theme included.
microsoftTeams.dialog.url.submit(result, appId)Sends result to your agent, which gets it as a task/submit invoke. Called with no arguments, it closes the dialog and sends nothing.

The agent answers that task/submit as it answered a card's in Part 10, and the answer decides what the dialog does next: continue with a url loads that page in the same dialog, message shows a text, and no answer closes the dialog. Here's one dialog from start to end:

In this part, one ASP.NET Core app is both ends of that diagram: it answers Teams' invokes at /api/messages, as every agent in this series does, and it serves the page from its wwwroot folder.

Some of Microsoft's pages still show microsoftTeams.tasks.submitTask, the name the call had before version 2.8.0 of TeamsJS. Its reference says: This API is now deprecated. As of 2.8.0, please use dialog.url.submit instead. This part uses dialog.url.submit.

The Example: Town Hall Seats​

The agent for this part is Town Hall Seats, in a one-to-one chat. Its card has a Pick a seat button that opens a dialog with the room's 24 seats, in four rows:

In the dialogWhat happens
The seat mapThe seats other people booked are faded, and your own seat is selected. The agent puts both in the page's address
Book seatThe page sends the seat to the agent. The agent books it, confirms it in the chat, and closes the dialog
A seat someone booked a moment agoThe agent shows the page again, with the seats as they are now and a message on top
CancelThe page sends nothing, and Teams closes the dialog

In this page, Leo Martin and Maya Patel book seats in a developer tenant: the steps follow Leo, and Maya is the second person in Steps 12 and 13. You'll write the code first, in steps, then run it in Teams:

StepYou addWhat you'll see
1The project
2The seat bookings
3–4The seat page: its HTML, CSS and JavaScript
5–7The page's address, the dialog's answer and the routes
8–9A tunnel, a bot and an app package, then run itTown Hall Seats in Teams, with its card
10–15Nothing: use the dialogThe page, a booking, a second person, a seat taken meanwhile, Cancel and the dark theme

Prerequisites​

  • Part 10, Teams Dialogs. This part reuses its setup: a dev tunnel, a Teams-managed bot, the agent's identity, token validation, a tenant filter and an app package, and its dialog routes.
  • The Teams developer CLI, signed in, to register the bot in one command. teams status shows whether you're signed in.
  • A second person in your Microsoft 365 tenant, or a second account, for Steps 12 and 13, where two people book seats at the same time.

Cost: nothing in this part needs an Azure subscription, as in Parts 8 to 10.

Step 1: Create the Project​

Create the project as in Part 10, with the same three packages:

Terminal 1
dotnet new web -o TownHallSeats
cd TownHallSeats
dotnet add package Microsoft.Agents.Hosting.AspNetCore --version 1.9.205
dotnet add package Microsoft.Agents.Authentication.Msal --version 1.9.205
dotnet add package Microsoft.Agents.Extensions.MSTeams --version 1.9.205
dotnet user-secrets init
Output (first and last lines)
The template "ASP.NET Core Empty" was created successfully.
...
info : PackageReference for package 'Microsoft.Agents.Hosting.AspNetCore' version '1.9.205' added to file '/Users/you/source/TownHallSeats/TownHallSeats.csproj'.
...
info : PackageReference for package 'Microsoft.Agents.Authentication.Msal' version '1.9.205' added to file '/Users/you/source/TownHallSeats/TownHallSeats.csproj'.
...
info : PackageReference for package 'Microsoft.Agents.Extensions.MSTeams' version '1.9.205' added to file '/Users/you/source/TownHallSeats/TownHallSeats.csproj'.
...
Set UserSecretsId to '00000000-0000-0000-0000-000000000000' for MSBuild project '/Users/you/source/TownHallSeats/TownHallSeats.csproj'.

Bring over the same three things as Part 10, changing only the namespace: AspNetExtensions.cs, the token validation code from Part 8, Step 5; TenantFilterMiddleware.cs, from Part 8, Step 10, with namespace TownHallSeats;; and appsettings.json, with "StartTypingTimer": false. Set the two applicationUrl lines in Properties/launchSettings.json to port 3978. Program.cs comes in Step 7, once everything it uses exists.

Step 2: Keep Track of the Seats​

SeatBookings holds the room's seats and who booked which one:

SeatBookings.cs
namespace TownHallSeats;

// The town hall's seats, and who has booked which one. Each person has one seat at most.
// The bookings live in memory, so they're gone when the agent stops.
public class SeatBookings
{
// The seats on the page, wwwroot/seats.html: rows A to D, seats 1 to 6.
public static readonly string[] AllSeats =
[
"A1", "A2", "A3", "A4", "A5", "A6",
"B1", "B2", "B3", "B4", "B5", "B6",
"C1", "C2", "C3", "C4", "C5", "C6",
"D1", "D2", "D3", "D4", "D5", "D6",
];

private readonly Lock _lock = new();
private readonly Dictionary<string, string> _seatByPerson = new();

// What one person sees: the seats other people have, and their own seat, if they have one.
public SeatMap MapFor(string personId)
{
lock (_lock)
{
_seatByPerson.TryGetValue(personId, out string? mine);
string[] taken = [.. _seatByPerson.Where(booking => booking.Key != personId).Select(booking => booking.Value)];
return new SeatMap(taken, mine);
}
}

// Books the seat for the person, unless someone else has it. A new seat replaces the person's old one.
public bool TryBook(string personId, string seat)
{
lock (_lock)
{
if (_seatByPerson.Any(booking => booking.Value == seat && booking.Key != personId))
{
return false;
}

_seatByPerson[personId] = seat;
return true;
}
}
}

// The seats other people have, and the person's own seat, or null.
public record SeatMap(string[] Taken, string? Mine);
  • AllSeats lists the 24 seats the page shows. The agent checks every seat the page sends against it.
  • _seatByPerson maps each person to their seat, so one person has one seat at most.
  • MapFor gives what one person sees: the seats other people have, and their own seat, or null.
  • TryBook books a seat unless someone else has it. A new seat replaces the person's old one.
  • lock (_lock): two people can book at the same moment, and the agent handles their requests side by side. The lock lets one booking finish before the next one looks at the seats, so two people can't both get the same seat. Lock is the lock type .NET has had since .NET 9.

The bookings live in memory, so they're gone when the agent stops. An agent people rely on keeps them in storage that lasts, which Part 20 covers.

Step 3: Build the Seat Page​

ASP.NET Core serves the files in a project's wwwroot folder as they are, once Step 7 turns that on. Create the folder, with the page first:

wwwroot/seats.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Pick your seat</title>
<link rel="stylesheet" href="seats.css">
</head>
<body>
<form id="seat-form">
<p id="message" hidden></p>
<p class="stage">Stage</p>
<div class="seats">
<label><input type="radio" name="seat" value="A1" required> A1</label>
<label><input type="radio" name="seat" value="A2" required> A2</label>
<label><input type="radio" name="seat" value="A3" required> A3</label>
<label><input type="radio" name="seat" value="A4" required> A4</label>
<label><input type="radio" name="seat" value="A5" required> A5</label>
<label><input type="radio" name="seat" value="A6" required> A6</label>
<label><input type="radio" name="seat" value="B1" required> B1</label>
<label><input type="radio" name="seat" value="B2" required> B2</label>
<label><input type="radio" name="seat" value="B3" required> B3</label>
<label><input type="radio" name="seat" value="B4" required> B4</label>
<label><input type="radio" name="seat" value="B5" required> B5</label>
<label><input type="radio" name="seat" value="B6" required> B6</label>
<label><input type="radio" name="seat" value="C1" required> C1</label>
<label><input type="radio" name="seat" value="C2" required> C2</label>
<label><input type="radio" name="seat" value="C3" required> C3</label>
<label><input type="radio" name="seat" value="C4" required> C4</label>
<label><input type="radio" name="seat" value="C5" required> C5</label>
<label><input type="radio" name="seat" value="C6" required> C6</label>
<label><input type="radio" name="seat" value="D1" required> D1</label>
<label><input type="radio" name="seat" value="D2" required> D2</label>
<label><input type="radio" name="seat" value="D3" required> D3</label>
<label><input type="radio" name="seat" value="D4" required> D4</label>
<label><input type="radio" name="seat" value="D5" required> D5</label>
<label><input type="radio" name="seat" value="D6" required> D6</label>
</div>
<button type="submit">Book seat</button>
<button type="button" id="cancel">Cancel</button>
</form>
<script src="https://res.cdn.office.net/teams-js/2.60.0/js/MicrosoftTeams.min.js"
integrity="sha384-oM1pbPWSxyAWgEVI9GzHDR2xzdMMehbAdsl9cH5emcTxX9Qr/kE4IS/Ld5IdcLmy"
crossorigin="anonymous"></script>
<script src="seats.js"></script>
</body>
</html>
  • The form, seat-form, holds the seats and the two buttons.
  • The message paragraph is where a problem from the agent goes. hidden keeps it out of sight until the script fills it in.
  • Each seat is a radio button inside its label, so selecting the seat's name selects the button too. All 24 share name="seat", so only one can be selected at a time, and value is what gets sent.
  • required on the radio buttons stops Book seat until a seat is selected. With none, the browser kept the page, with its own message, Please select one of these options., and the agent got nothing.
  • type="submit" makes Book seat submit the form. type="button" keeps Cancel from submitting it: the script decides what Cancel does.
  • The TeamsJS tag loads version 2.60.0, the newest, from Microsoft's CDN. integrity makes the browser check that the file is exactly the one Microsoft published, and crossorigin="anonymous" is what that check needs for a file from another site. How to Add the Teams JavaScript Library (TeamsJS) to a Web Page from the CDN covers the tag on its own.
  • seats.js loads last, after TeamsJS and after the seats exist on the page.

Then the page's style:

wwwroot/seats.css
/* Colors for Teams' default theme. The dark theme replaces them below. */
body {
--text: #242424;
--background: #ffffff;
--border: #d1d1d1;
--accent: #5b5fc7;
--button: #5b5fc7;
--error: #c50f1f;
margin: 0;
padding: 0 24px 16px;
font-family: "Segoe UI", system-ui, sans-serif;
font-size: 14px;
color: var(--text);
background: var(--background);
accent-color: var(--accent);
}

body[data-theme="dark"] {
--text: #ffffff;
--background: #292929;
--border: #5c5c5c;
--accent: #7f85f5;
--button: #4f52b2;
--error: #f1707b;
color-scheme: dark;
}

#message {
color: var(--error);
font-weight: 600;
}

.stage {
padding: 6px;
text-align: center;
border: 1px solid var(--border);
border-radius: 4px;
}

/* Six seats in each row. A seat someone else has is faded. */
.seats {
display: grid;
grid-template-columns: repeat(6, 1fr);
gap: 10px;
margin-bottom: 18px;
}

.seats label:has(:disabled) {
opacity: 0.4;
}

button {
padding: 5px 20px;
border: 1px solid var(--border);
border-radius: 4px;
font: inherit;
font-weight: 600;
color: var(--text);
background: var(--background);
}

/* The main button: white text on a color dark enough to read it in both themes. */
button[type="submit"] {
border-color: var(--button);
color: #ffffff;
background: var(--button);
}
  • The colors are variables on body: the text, the background, the borders, the accent, the main button and the error message.
  • body[data-theme="dark"] gives the dark theme its own values. The script writes Teams' theme into the body's data-theme attribute, in Step 4. color-scheme: dark tells the browser to draw its own controls, such as an empty radio button, for a dark background.
  • The page paints its own background. A page that leaves its background transparent shows Teams' dialog through it, and in the dark theme its text can end up black on dark grey: Fixed: Black Text on a Dark Background in a Teams Dialog.
  • .seats lays the seats out in a grid of six columns, so the 24 seats make four rows.
  • .seats label:has(:disabled) fades the label of a seat that can't be picked. The script disables the seats other people have.
  • accent-color colors the selected radio button, and button[type="submit"] gives Book seat white text on the main color.

Step 4: Connect the Page to Teams​

The script, a piece at a time. First, what the page reads before it connects:

wwwroot/seats.js (the first lines)
// Your Teams app's ID, from its manifest. Microsoft's docs ask for it with every result.
const appId = "22222222-2222-2222-2222-222222222222";

const query = new URLSearchParams(window.location.search);
const taken = (query.get("taken") ?? "").split(",");
  • appId is your Teams app's ID, the id in its manifest.json. The value here is a placeholder until Step 8 gives you yours. Microsoft's Use dialogs in tabs asks for it: If you call submit() with a result parameter, you must pass an appId (or an array of appId strings of apps authorized to receive the result of the dialog). This action enables Teams to validate that the app sending the result is the same as the invoked dialog.
  • query reads the part of the page's address after the ?, where the agent puts taken, mine and message.
  • taken is the list of seats other people have: B3,C4 becomes ["B3", "C4"]. With no taken in the address, ?? gives an empty text instead, and the list matches no seat.

Then start, which connects the page to Teams and reads Teams' theme:

wwwroot/seats.js (start, the first half)
async function start() {
// Connect the page to Teams. Every other TeamsJS call needs this first.
await microsoftTeams.app.initialize();

// Teams' theme: "default", "dark" or "contrast". seats.css has dark colors; the others use its default ones.
const context = await microsoftTeams.app.getContext();
document.body.dataset.theme = context.app.theme;
  • microsoftTeams is what the TeamsJS tag gives the page.
  • await microsoftTeams.app.initialize() connects the page to Teams, and await waits until it has, before any other TeamsJS call.
  • getContext() gives the page its context, and context.app.theme is Teams' theme. Its reference describes it as The current UI theme of the host. Possible values: "default", "dark", "contrast" or "glass". The next line writes it into the body's data-theme attribute, which seats.css reads. How to Match the Microsoft Teams Theme in a Web Page with TeamsJS shows this on its own.
  • The page reads the theme itself. The task/fetch request carries a context.theme too, but in Teams on the web it said default in the dark and high contrast themes as well, as Fixed: "theme": "default" in a Teams task/fetch Request While Teams Is in Dark Theme shows.

The rest of start sets up the seats, the message and the buttons:

wwwroot/seats.js (start, the second half)
for (const seat of document.querySelectorAll("input[name=seat]")) {
seat.disabled = taken.includes(seat.value);
seat.checked = seat.value === query.get("mine");
}

const message = query.get("message");
if (message) {
const box = document.getElementById("message");
box.textContent = message;
box.hidden = false;
}

document.getElementById("seat-form").addEventListener("submit", book);
document.getElementById("cancel").addEventListener("click", cancel);
}
  • The loop goes through the 24 radio buttons. A seat in taken is disabled, so it can't be picked, and seats.css fades it. The seat in mine is selected.
  • message, when the address has one, goes into the hidden paragraph, which then shows. textContent puts it in as plain text, never as HTML, so nothing in the address can add markup or scripts to the page.
  • The last two lines connect the buttons: submitting the form runs book, and selecting Cancel runs cancel. Both call TeamsJS, so they're connected after initialize().

book sends the selected seat to the agent:

wwwroot/seats.js (book)
// Book seat: Teams sends the result to the agent, as task/submit.
function book(event) {
event.preventDefault();
const seat = document.querySelector("input[name=seat]:checked").value;
microsoftTeams.dialog.url.submit({ task: "book", seat }, appId);
}
  • event.preventDefault() stops the browser's own form submit, which would load another page in the dialog. TeamsJS sends the result instead.
  • seat is the selected seat's value, such as "B3". required made sure there is one.
  • dialog.url.submit({ task: "book", seat }, appId) sends the object to the agent, with the app's ID. { task: "book", seat } is short for { task: "book", seat: seat }. Its task is the key that TeamsExtension.TaskModules.OnSubmit matches, as a card button's data was in Part 10.

cancel closes the dialog without a result, and the last line starts it all:

wwwroot/seats.js (cancel)
// Cancel: no result, so Teams just closes the dialog.
function cancel() {
microsoftTeams.dialog.url.submit();
}

start();

The whole file:

wwwroot/seats.js
// Town Hall Seats' seat page. The agent puts what it shows in the page's address:
// taken (the seats other people have), mine (your seat, if you have one) and message (a problem to show).

// Your Teams app's ID, from its manifest. Microsoft's docs ask for it with every result.
const appId = "22222222-2222-2222-2222-222222222222";

const query = new URLSearchParams(window.location.search);
const taken = (query.get("taken") ?? "").split(",");

async function start() {
// Connect the page to Teams. Every other TeamsJS call needs this first.
await microsoftTeams.app.initialize();

// Teams' theme: "default", "dark" or "contrast". seats.css has dark colors; the others use its default ones.
const context = await microsoftTeams.app.getContext();
document.body.dataset.theme = context.app.theme;

for (const seat of document.querySelectorAll("input[name=seat]")) {
seat.disabled = taken.includes(seat.value);
seat.checked = seat.value === query.get("mine");
}

const message = query.get("message");
if (message) {
const box = document.getElementById("message");
box.textContent = message;
box.hidden = false;
}

document.getElementById("seat-form").addEventListener("submit", book);
document.getElementById("cancel").addEventListener("click", cancel);
}

// Book seat: Teams sends the result to the agent, as task/submit.
function book(event) {
event.preventDefault();
const seat = document.querySelector("input[name=seat]:checked").value;
microsoftTeams.dialog.url.submit({ task: "book", seat }, appId);
}

// Cancel: no result, so Teams just closes the dialog.
function cancel() {
microsoftTeams.dialog.url.submit();
}

start();

seats.js in a macOS-style editor window: the page reads taken from its address with URLSearchParams, start awaits microsoftTeams.app.initialize, writes context.app.theme from getContext into the body's data-theme, disables taken seats and selects the person's own, shows the agent's message, and connects the buttons; book calls microsoftTeams.dialog.url.submit with the task book, the seat and the app ID, and cancel calls submit with no arguments

Step 5: Give Teams the Page's Address​

SeatPage builds the address the agent gives Teams, and holds the header that lets only Teams show the page in a frame:

SeatPage.cs
using Microsoft.AspNetCore.WebUtilities;

namespace TownHallSeats;

// The web page Teams shows in the dialog, and the address the agent gives Teams for it.
public class SeatPage
{
// Teams shows the page inside its own page. This Content-Security-Policy lets only Teams do that.
public const string ContentSecurityPolicy =
"frame-ancestors https://teams.microsoft.com https://*.teams.microsoft.com https://*.cloud.microsoft";

private readonly string _pageUrl;

public SeatPage(IConfiguration configuration)
{
// PublicUrl is the agent's public HTTPS address: the dev tunnel's, without a path.
string? publicUrl = configuration["PublicUrl"];

if (!Uri.TryCreate(publicUrl, UriKind.Absolute, out Uri? baseUrl) || baseUrl.Scheme != Uri.UriSchemeHttps)
{
throw new InvalidOperationException("Set PublicUrl in appsettings.Development.json to your dev tunnel's https:// address.");
}

_pageUrl = new Uri(baseUrl, "seats.html").ToString();
}

// The page's address, with what it shows in the query string:
// taken (other people's seats), mine (the person's seat) and message (a problem to show).
public string UrlFor(SeatMap map, string? message = null)
{
Dictionary<string, string?> query = new() { ["taken"] = string.Join(',', map.Taken) };

if (map.Mine is not null)
{
query["mine"] = map.Mine;
}

if (message is not null)
{
query["message"] = message;
}

return QueryHelpers.AddQueryString(_pageUrl, query);
}
}
  • ContentSecurityPolicy is the header value Step 7 sends with every response. Its frame-ancestors lists the only sites allowed to show the page in a frame: Teams' two values and *.cloud.microsoft, from the table in Microsoft's requirements for tabs, which asks to keep the older values while Microsoft 365 moves to *.cloud.microsoft. A browser refuses to show the page inside any other site, so no other site can wrap it in its own page to trick people into clicking it, an attack called clickjacking.
  • *.cloud.microsoft matters today. Teams on the web ran at teams.cloud.microsoft, and with only the two older values the dialog said the site refused to connect: Fixed: Framing '…' Violates the Following Content Security Policy Directive: "frame-ancestors …" in a Teams Dialog.
  • PublicUrl is the agent's public address, the dev tunnel's, which Step 8 puts in appsettings.Development.json. The constructor checks that it's an absolute https:// address, since a dialog's url must use HTTPS, and stops with a message that says what to fix.
  • new Uri(baseUrl, "seats.html") puts the page's file name after that address.
  • UrlFor adds what the page shows to the address's query string: taken, the seats other people have, joined with commas; mine, when the person has a seat; and message, when there's a problem to show. QueryHelpers.AddQueryString encodes each value, so a message with spaces travels safely. How to Add a Query String to a URL with QueryHelpers.AddQueryString in ASP.NET Core (C#) shows it on its own.

The address carries everything the page shows, so the page needs no data of its own: it never has to ask the agent who the person is. Anyone can read and change an address, though, which is why the agent checks again what the page sends back, in Step 7.

Step 6: Answer with the Page​

SeatDialogs builds the card in the chat and the answer that opens the page:

SeatDialogs.cs
using System.Text.Json.Nodes;
using Microsoft.Teams.Apps.TaskModules;

namespace TownHallSeats;

// The card in the chat, and the answer that opens the seat page in a dialog.
public static class SeatDialogs
{
// The card in the chat. msteams.type "task/fetch" makes its button open a dialog,
// and "task" tells the agent which dialog to show.
public static JsonObject Launcher() => new()
{
["type"] = "AdaptiveCard",
["version"] = "1.5",
["body"] = new JsonArray
{
new JsonObject { ["type"] = "TextBlock", ["text"] = "Town hall", ["size"] = "Large", ["weight"] = "Bolder" },
new JsonObject { ["type"] = "TextBlock", ["text"] = "Thursday at 10:00 in Room 3.14. Pick where you'd like to sit.", ["wrap"] = true },
},
["actions"] = new JsonArray
{
new JsonObject
{
["type"] = "Action.Submit",
["title"] = "Pick a seat",
["data"] = new JsonObject
{
["msteams"] = new JsonObject { ["type"] = "task/fetch" },
["task"] = "seats",
},
},
},
};

// "continue" with a url: Teams opens the dialog, or keeps it open, and loads this page in it.
// width and height are in pixels: the page's size, without the title bar Teams adds above it.
public static TaskModuleResponse ShowPage(string url) => new()
{
Task = new Response
{
Type = TaskModuleResponseTypes.Continue,
Value = new
{
title = "Pick your seat",
width = 600,
height = 270,
url,
},
},
};
}
  • Launcher is the card in the chat, built like Part 10's: its button's data has "msteams": { "type": "task/fetch" }, so Teams asks the agent for a dialog, and "task": "seats" names the dialog.
  • ShowPage answers continue with a url, where Part 10's answer had a card. Its Value is an anonymous object whose property names become the JSON names Teams expects: title, width, height and url.
  • width and height are numbers, in pixels. In Teams on the web, the page got exactly 600 by 270, with Teams' title bar above it. Microsoft's docs add that depending on the size of the Teams window and screen resolution, these values might be reduced proportionally while maintaining aspect ratio. How to Set the Size of a Teams Dialog in the Microsoft 365 Agents SDK in C# compares the sizes you can ask for.

Step 7: Route the Dialog​

The agent class connects the dialog to the bookings. Here are its constructor and its two dialog handlers:

TownHallAgent.cs (excerpt)
public TownHallAgent(AgentApplicationOptions options, SeatBookings bookings, SeatPage seatPage, ILogger<TownHallAgent> logger)
: base(options)
{
_bookings = bookings;
_seatPage = seatPage;
_logger = logger;

OnConversationUpdate(ConversationUpdateEvents.MembersAdded, WelcomeAsync);
OnActivity(ActivityTypes.Message, ShowLauncherAsync);

TeamsExtension.TaskModules.OnFetch("seats", OpenSeatPageAsync);
TeamsExtension.TaskModules.OnSubmit("book", BookAsync);
}

// task/fetch: Teams asks what to show. The answer is the seat page, for this person.
private Task<TaskModuleResponse> OpenSeatPageAsync(ITeamsTurnContext turnContext, ITurnState turnState, TaskModuleRequest request, CancellationToken cancellationToken)
{
SeatMap map = _bookings.MapFor(PersonId(turnContext));
return Task.FromResult(SeatDialogs.ShowPage(_seatPage.UrlFor(map)));
}

// task/submit from the page: book the seat it sent. Booked: close the dialog and confirm in the chat.
// Otherwise: the page again, with the seats as they are now and the problem on top.
private async Task<TaskModuleResponse> BookAsync(ITeamsTurnContext turnContext, ITurnState turnState, TaskModuleRequest request, CancellationToken cancellationToken)
{
string personId = PersonId(turnContext);
string seat = request.GetDataString("seat", "");

// The page runs on the person's device, so check what it sent: a real seat, and still free.
if (!SeatBookings.AllSeats.Contains(seat))
{
return SeatDialogs.ShowPage(_seatPage.UrlFor(_bookings.MapFor(personId), "Pick a seat on the map."));
}

if (!_bookings.TryBook(personId, seat))
{
return SeatDialogs.ShowPage(_seatPage.UrlFor(_bookings.MapFor(personId), $"Seat {seat} was just taken. Pick another one."));
}

_logger.LogInformation("Seat {Seat} booked.", seat);
await turnContext.SendActivityAsync($"You're in seat {seat}. See you at the town hall!", cancellationToken: cancellationToken);
return null!;
}
  • OnFetch("seats", OpenSeatPageAsync) answers the card's button with the seat page, its address built for this person: the seats other people have, and theirs.
  • OnSubmit("book", BookAsync) handles the page's result. Its task, "book", comes from the object the page passed to dialog.url.submit, and GetDataString("seat", "") reads its seat, or "" when there's none.
  • Two checks come first, because the page runs on the person's device and what it sends could be anything. A seat that isn't on the map gets the page again with Pick a seat on the map. A seat someone else booked since the page opened gets the page again with the seats as they are now and Seat … was just taken. Pick another one.
  • A booked seat is logged, confirmed in the chat with SendActivityAsync, and answered with null!: no answer, so Teams closes the dialog, as Part 10's Cancel did.
  • PersonId, in the complete class below, is the person's Microsoft Entra object ID, AadObjectId, which is the same in every chat. The bookings are kept by it.

The whole class is in The Complete Code. Now Program.cs:

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

var builder = WebApplication.CreateBuilder(args);

string[] allowedTenants = builder.Configuration.GetSection("AllowedTenants").Get<string[]>() ?? [];
if (allowedTenants.Length == 0)
{
throw new InvalidOperationException("Add your Microsoft Entra tenant ID to AllowedTenants in appsettings.json.");
}

builder.AddAgentDefaults()
.AddAgent<TownHallAgent>()
.AddAgentMiddleware(new TenantFilterMiddleware(allowedTenants))
.AddAgentAuthorization(b => b.AddAgentAspNetAuthentication(), forceEnable: true);
builder.Services.AddSingleton<IStorage, MemoryStorage>();
builder.Services.AddSingleton<SeatBookings>();
builder.Services.AddSingleton<SeatPage>();

var app = builder.Build();

// Every response says which sites may show it inside their own page: only Teams.
app.Use(async (context, next) =>
{
context.Response.Headers.ContentSecurityPolicy = SeatPage.ContentSecurityPolicy;
await next(context);
});

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

app.Run();

Part 10's Program.cs, with three changes:

With the routes in place, the agent's code is complete, and the rest is registering it and trying it.

Step 8: Register Town Hall Seats in Teams​

Town Hall Seats needs what Supply Desk had in Part 10, plus its page's domain in the manifest.

A dev tunnel, in a second terminal:

Terminal 2
devtunnel create town-hall-seats --allow-anonymous
devtunnel port create town-hall-seats -p 3978
devtunnel host town-hall-seats
Output (the last command)
Connection to host tunnel relay restored.
Hosting port: 3978
Connect via browser: https://cdzngt35-3978.inc1.devtunnels.ms
Inspect network activity: https://cdzngt35-3978-inspect.inc1.devtunnels.ms

Ready to accept connections for tunnel: town-hall-seats.inc1

The page's address, in appsettings.Development.json: put the tunnel's address from that output in PublicUrl. Add one more log level too, so you can watch Teams load the page:

appsettings.Development.json
{
"PublicUrl": "https://cdzngt35-3978.inc1.devtunnels.ms",
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning",
"Microsoft.AspNetCore.Hosting.Diagnostics": "Information"
}
}
}
  • PublicUrl has no path and no slash at the end: SeatPage adds seats.html to it.
  • Microsoft.AspNetCore.Hosting.Diagnostics is the logging category that writes a line when each request starts and ends. Its own level wins over "Microsoft.AspNetCore": "Warning", because the most specific category wins, as How to Set Different Log Levels per Environment in appsettings.json shows.

A bot, registered with the Teams developer CLI in a third terminal, as in How to Register a Bot with the Teams Developer CLI. Use your tunnel's address, keep the credentials in a file outside the project, and give it the icons from your app package:

Terminal 3
teams app create --name "Town Hall Seats" --endpoint "https://cdzngt35-3978.inc1.devtunnels.ms/api/messages" --env ./townhallseats.json --color-icon color.png --outline-icon outline.png
Output
- Acquiring tokens...
✔ Tokens acquired
- Creating Azure AD app...
✔ Created Azure AD app (00000000-0000-0000-0000-000000000000)
- Generating client secret...
✔ Generated client secret
- Creating Teams app...
✔ Created Teams app (00000000-0000-0000-0000-000000000000)
- Registering bot...
✔ Bot registered

App created successfully!
Name: Town Hall Seats
Teams App ID: 00000000-0000-0000-0000-000000000000
Bot ID: 00000000-0000-0000-0000-000000000000
Endpoint: https://cdzngt35-3978.inc1.devtunnels.ms/api/messages

▸ Install in Teams → https://teams.microsoft.com/l/app/00000000-0000-0000-0000-000000000000?installAppPackage=true&appTenantId=11111111-1111-1111-1111-111111111111
▸ Developer Portal → https://dev.teams.microsoft.com/apps/00000000-0000-0000-0000-000000000000
Credentials written to ./townhallseats.json

The agent's identity, in user secrets, with the values from the file, exactly as in Part 10:

Terminal 1
dotnet user-secrets set "Connections:ServiceConnection:Settings:ClientId" "<bot ID>"
dotnet user-secrets set "Connections:ServiceConnection:Settings:ClientSecret" "<client secret>"
dotnet user-secrets set "Connections:ServiceConnection:Settings:AuthorityEndpoint" "https://login.microsoftonline.com/<tenant ID>"
dotnet user-secrets set "TokenValidation:Audiences:0" "<bot ID>"
dotnet user-secrets set "TokenValidation:TenantId" "<tenant ID>"
dotnet user-secrets set "AllowedTenants:0" "<tenant ID>"

Then delete townhallseats.json: the secret shouldn't sit in a file.

An app package, with one addition to Part 10's manifest: validDomains.

appPackage/manifest.json
{
"$schema": "https://developer.microsoft.com/json-schemas/teams/v1.30/MicrosoftTeams.schema.json",
"manifestVersion": "1.30",
"version": "1.0.0",
"id": "22222222-2222-2222-2222-222222222222",
"developer": {
"name": "Contoso",
"websiteUrl": "https://www.example.com",
"privacyUrl": "https://www.example.com/privacy",
"termsOfUseUrl": "https://www.example.com/terms"
},
"name": {
"short": "Town Hall Seats",
"full": "Town Hall Seats"
},
"description": {
"short": "Books your seat for the town hall.",
"full": "Chat with Town Hall Seats and select Pick a seat: a dialog shows the room's seats, and you book a free one. A sample agent built with the Microsoft 365 Agents SDK."
},
"icons": {
"color": "color.png",
"outline": "outline.png"
},
"accentColor": "#6A1B9A",
"bots": [
{
"botId": "22222222-2222-2222-2222-222222222222",
"scopes": [
"personal"
],
"supportsFiles": false,
"isNotificationOnly": false
}
],
"validDomains": [
"cdzngt35-3978.inc1.devtunnels.ms"
]
}

The app's ID in the page. Open wwwroot/seats.js and put the same ID, the manifest's id, in appId, in place of the placeholder.

Step 9: Run the Agent and Add It​

In Terminal 1:

Terminal 1
dotnet run
Output
Using launch settings from /Users/you/source/TownHallSeats/Properties/launchSettings.json...
Building...
info: Microsoft.Agents.Authentication.ConfigurationConnections[0]
No assembly name given in config for connection `ServiceConnection`. Using default assembly lib: `Microsoft.Agents.Authentication.Msal`
info: Microsoft.Agents.Authentication.ConfigurationConnections[0]
No type name given in config for connection `ServiceConnection`. Using default type name: `MsalAuth`
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/TownHallSeats

Upload the package as a custom app, as in How to Upload a Custom App in Microsoft Teams: Store, Manage your apps, Upload an app, Upload a custom app. Teams shows Town Hall Seats' details:

The Town Hall Seats dialog by Contoso with an Add button, 0 installs in the last month, Works in Teams, Free, the description Books your seat for the town hall., and Bot under Capabilities in Teams

Select Add, then Open. Adding the app starts the chat, and Town Hall Seats answers that with its card:

Town Hall Seats' card in its chat: Town hall, Thursday at 10:00 in Room 3.14. Pick where you'd like to sit., and a Pick a seat button

Step 10: Open the Seat Page​

Select Pick a seat. Teams asks the agent for the dialog, and loads the page the answer points to:

A Teams dialog with the Town Hall Seats icon and name, the title Pick your seat and an X, showing the seat page: a Stage bar, 24 empty radio buttons from A1 to D6 in four rows of six, and Book seat and Cancel buttons

Teams drew the icon, the app's name, the title from the answer and the X. Everything under them is the page. The task/fetch invoke's value:

task/fetch value
{
"data": {
"task": "seats",
"type": "task/fetch"
},
"context": {
"theme": "default"
}
}

The agent answered with continue and a url. No one had a seat yet, so taken was empty:

The answer
{
"status": 200,
"body": {
"task": {
"type": "continue",
"value": {
"title": "Pick your seat",
"width": 600,
"height": 270,
"url": "https://cdzngt35-3978.inc1.devtunnels.ms/seats.html?taken="
}
}
}
}

The request log in Terminal 1 shows the order: first the task/fetch invoke and its answer, then Teams loading the page from that address, and the page loading its style and its script:

Terminal 1
info: Microsoft.AspNetCore.Hosting.Diagnostics[1]
Request starting HTTP/1.1 POST http://localhost:3978/api/messages - application/json;+charset=utf-8 1420
info: Microsoft.AspNetCore.Hosting.Diagnostics[2]
Request finished HTTP/1.1 POST http://localhost:3978/api/messages - 200 - application/json;+charset=utf-8 1431.3782ms
info: Microsoft.AspNetCore.Hosting.Diagnostics[1]
Request starting HTTP/1.1 GET http://localhost:3978/seats.html?taken= - - -
info: Microsoft.AspNetCore.Hosting.Diagnostics[2]
Request finished HTTP/1.1 GET http://localhost:3978/seats.html?taken= - 200 2540 text/html 17.2822ms
info: Microsoft.AspNetCore.Hosting.Diagnostics[1]
Request starting HTTP/1.1 GET http://localhost:3978/seats.css - - -
info: Microsoft.AspNetCore.Hosting.Diagnostics[2]
Request finished HTTP/1.1 GET http://localhost:3978/seats.css - 200 1367 text/css 2.5014ms
info: Microsoft.AspNetCore.Hosting.Diagnostics[1]
Request starting HTTP/1.1 GET http://localhost:3978/seats.js - - -
info: Microsoft.AspNetCore.Hosting.Diagnostics[2]
Request finished HTTP/1.1 GET http://localhost:3978/seats.js - 200 1721 text/javascript 1.7476ms

The requests arrive at localhost:3978 because the tunnel passes them on from its public address. The first time a browser opens a page through a dev tunnel, the dialog can show the tunnel's own warning page first: Fixed: "You Are About to Connect to a Developer Tunnel" in a Teams Dialog shows how to get past it.

Step 11: Book a Seat​

Select B3:

The seat page with B3 selected and every other seat empty

Select Book seat. The dialog closes, and the agent confirms in the chat:

A message from Town Hall Seats: You're in seat B3. See you at the town hall!

The page's result arrived as a task/submit invoke, with the object the page passed to dialog.url.submit as its data:

task/submit value
{
"data": {
"task": "book",
"seat": "B3"
},
"context": {
"theme": "default"
}
}

The agent booked the seat and logged it:

Terminal 1
info: TownHallSeats.TownHallAgent[0]
Seat B3 booked.

Its answer was a 200 with no body, for the null that BookAsync returned, and Teams closed the dialog:

The answer
{
"status": 200
}

Step 12: Book as a Second Person​

Open the dialog again and leave it open. B3, your seat, is selected, because the agent's address now had mine=B3:

Terminal 1
info: Microsoft.AspNetCore.Hosting.Diagnostics[1]
Request starting HTTP/1.1 GET http://localhost:3978/seats.html?taken=&mine=B3 - - -

Now the second person, Maya, uploads the same app package in Maya's own Teams, adds Town Hall Seats and selects Pick a seat. B3 is faded on Maya's page, because it's yours:

Maya's seat page: B3 is faded and can't be selected, and every other seat is free

Maya's address listed it in taken:

Terminal 1
info: Microsoft.AspNetCore.Hosting.Diagnostics[1]
Request starting HTTP/1.1 GET http://localhost:3978/seats.html?taken=B3 - - -

Maya selects C4 and Book seat, and gets a confirmation too:

In Maya's chat, a message from Town Hall Seats at 10:31 AM: You're in seat C4. See you at the town hall!

Step 13: Book a Seat Someone Just Took​

Back in your dialog, which opened before Maya booked, C4 still looks free. Select C4 and Book seat. The agent's TryBook finds C4 taken, and it answers with the page again:

The seat page in the same dialog with a red message on top, Seat C4 was just taken. Pick another one., C4 faded and B3 still selected

The dialog stayed open and loaded the new address, with C4 in taken, B3 still yours, and the message:

Terminal 1
info: Microsoft.AspNetCore.Hosting.Diagnostics[1]
Request starting HTTP/1.1 GET http://localhost:3978/seats.html?taken=C4&mine=B3&message=Seat%20C4%20was%20just%20taken.%20Pick%20another%20one. - - -

TeamsJS's reference describes dialog.url.submit as Submit the dialog module and close the dialog. For a dialog your agent opened, what happens next is the agent's answer: a continue with a url kept this one open with a new page. This check is one only the agent can make, because only the agent knows the bookings as they are now.

Step 14: Cancel​

Open the dialog and select Cancel. It closes, nothing appears in the chat, and Terminal 1 shows no new request: submit() with no arguments gives Teams nothing to send the agent.

Closing the dialog with Teams' X gave the same result: the dialog closed, and the agent got nothing.

Step 15: Check the Dark Theme​

Switch Teams to its dark theme, as in How to Switch Microsoft Teams to Dark Theme, and select Pick a seat again:

The seat page in Teams' dark theme: dark grey background, white text and seat names, dark radio buttons, B3 selected in light purple, C4 faded, and a purple Book seat button

The page read dark from getContext(), wrote it into data-theme, and seats.css used its dark colors. In the same dark theme, the task/fetch invoke still said "theme": "default", so reading the theme in the page was the right call. Switch Teams back to the theme you use.

When the Page Doesn't Load​

Each of these happened while building this part's examples, and each has its own fix:

What you seeWhat it meansThe fix
An empty dialog, then If you're having issues with this app, try the desktop versionTeams didn't load the page: its domain isn't in validDomains, and the request log has no GET for it. A page that never calls app.initialize() got the same banner, about 30 seconds after it loadedFixed: "If You're Having Issues with This App, Try the Desktop Version" in a Teams Dialog
A page about connecting to a developer tunnelThe dev tunnel's warning, shown once for each browser and addressFixed: "You Are About to Connect to a Developer Tunnel" in a Teams Dialog
refused to connect in the dialogThe page's frame-ancestors leaves out the address Teams runs atFixed: Framing '…' Violates the Following Content Security Policy Directive: "frame-ancestors …" in a Teams Dialog
Black text on a dark dialogThe page has no colors of its own for the dark themeFixed: Black Text on a Dark Background in a Teams Dialog

The Complete Code​

TownHallAgent.cs
using Microsoft.Agents.Builder;
using Microsoft.Agents.Builder.App;
using Microsoft.Agents.Builder.State;
using Microsoft.Agents.Core.Models;
using Microsoft.Agents.Extensions.MSTeams;
using Microsoft.Teams.Apps.TaskModules;

namespace TownHallSeats;

[TeamsExtension]
public partial class TownHallAgent : AgentApplication
{
private readonly SeatBookings _bookings;
private readonly SeatPage _seatPage;
private readonly ILogger<TownHallAgent> _logger;

public TownHallAgent(AgentApplicationOptions options, SeatBookings bookings, SeatPage seatPage, ILogger<TownHallAgent> logger)
: base(options)
{
_bookings = bookings;
_seatPage = seatPage;
_logger = logger;

OnConversationUpdate(ConversationUpdateEvents.MembersAdded, WelcomeAsync);
OnActivity(ActivityTypes.Message, ShowLauncherAsync);

TeamsExtension.TaskModules.OnFetch("seats", OpenSeatPageAsync);
TeamsExtension.TaskModules.OnSubmit("book", BookAsync);
}

// When someone adds Town Hall Seats, the agent itself is among the members added.
private async Task WelcomeAsync(ITurnContext turnContext, ITurnState turnState, CancellationToken cancellationToken)
{
if (turnContext.Activity.MembersAdded.Any(member => member.Id == turnContext.Activity.Recipient.Id))
{
await turnContext.SendActivityAsync(LauncherMessage(), cancellationToken);
}
}

// Any message gets the card with the button that opens the dialog.
private Task ShowLauncherAsync(ITurnContext turnContext, ITurnState turnState, CancellationToken cancellationToken)
{
return turnContext.SendActivityAsync(LauncherMessage(), cancellationToken);
}

// task/fetch: Teams asks what to show. The answer is the seat page, for this person.
private Task<TaskModuleResponse> OpenSeatPageAsync(ITeamsTurnContext turnContext, ITurnState turnState, TaskModuleRequest request, CancellationToken cancellationToken)
{
SeatMap map = _bookings.MapFor(PersonId(turnContext));
return Task.FromResult(SeatDialogs.ShowPage(_seatPage.UrlFor(map)));
}

// task/submit from the page: book the seat it sent. Booked: close the dialog and confirm in the chat.
// Otherwise: the page again, with the seats as they are now and the problem on top.
private async Task<TaskModuleResponse> BookAsync(ITeamsTurnContext turnContext, ITurnState turnState, TaskModuleRequest request, CancellationToken cancellationToken)
{
string personId = PersonId(turnContext);
string seat = request.GetDataString("seat", "");

// The page runs on the person's device, so check what it sent: a real seat, and still free.
if (!SeatBookings.AllSeats.Contains(seat))
{
return SeatDialogs.ShowPage(_seatPage.UrlFor(_bookings.MapFor(personId), "Pick a seat on the map."));
}

if (!_bookings.TryBook(personId, seat))
{
return SeatDialogs.ShowPage(_seatPage.UrlFor(_bookings.MapFor(personId), $"Seat {seat} was just taken. Pick another one."));
}

_logger.LogInformation("Seat {Seat} booked.", seat);
await turnContext.SendActivityAsync($"You're in seat {seat}. See you at the town hall!", cancellationToken: cancellationToken);
return null!;
}

// The person's Microsoft Entra object ID: the same in every chat and on every device.
private static string PersonId(ITurnContext turnContext) =>
turnContext.Activity.From.AadObjectId ?? turnContext.Activity.From.Id;

private static IActivity LauncherMessage() =>
MessageFactory.Attachment(new Attachment { ContentType = ContentTypes.AdaptiveCard, Content = SeatDialogs.Launcher() });
}

SeatBookings.cs, the three files in wwwroot, SeatPage.cs, SeatDialogs.cs, Program.cs, appsettings.Development.json and appPackage/manifest.json are complete in Steps 2 to 8.

Stop and Clean Up​

Everything this part created outside your project folder stays until you remove it:

  1. Stop the agent and the tunnel host with Ctrl+C in their terminals.

  2. Uninstall Town Hall Seats in Teams, for each person who added it: How to Uninstall an App in Microsoft Teams.

  3. Delete the app under Apps in the Teams Developer Portal: How to Delete an App in the Teams Developer Portal.

  4. Delete the bot under Tools > Bot management: How to Delete a Bot in the Teams Developer Portal.

  5. Delete the app registration, which neither of the portal's deletes removes: How to Delete an App Registration in Microsoft Entra ID.

  6. Delete the tunnel:

    Terminal
    devtunnel delete town-hall-seats -f
    Output
    Deleted: town-hall-seats.inc1
  7. Remove the client secret from your machine: dotnet user-secrets clear, in the project folder, deletes the project's user secrets and prints nothing.

What You Can Do Now​

  • Answer task/fetch with continue and a url, to show your own page in a Teams dialog, at a size in pixels.
  • Get a page ready for Teams: an HTTPS address, its domain in validDomains, and a frame-ancestors list that lets only Teams frame it.
  • Connect a page to Teams with app.initialize(), and read Teams' theme with app.getContext().
  • Send a page's result to your agent with dialog.url.submit, with your app's ID, and close the dialog with submit().
  • Pass what a page shows in its address, and check what it sends back in the agent.
  • Answer a page's result with another page in the same dialog, or close the dialog with no answer.

Common Mistakes​

MistakeWhat happensDo this instead
Leaving the page's domain out of validDomainsAn empty dialog, then If you're having issues with this app, try the desktop versionAdd the host name, raise the manifest's version, and upload the package again
A frame-ancestors list without https://*.cloud.microsoftrefused to connect in Teams on the webAdd it, and keep Teams' two older values
Reading the theme from the task/fetch request's context.themeIt said default in the dark theme, and the page stayed light-styledRead context.app.theme with getContext() in the page
Leaving the page's background transparentTeams' dialog shows through, and in the dark theme the text can end up black on dark greyGive the page its own background and text colors
Trusting the seat the page sendsA page runs on the person's device, so what it sends could be anythingCheck it in the agent, as BookAsync does

Troubleshooting​

SymptomLikely causeFix
The dialog stays empty, and the request log has no GET for the pageThe page's domain isn't in validDomainsAdd it, as in Step 8
refused to connect in the dialogThe Content-Security-Policy doesn't allow the address Teams runs atUse the three frame-ancestors values from Step 5
A page about a developer tunnel in the dialogThe dev tunnel's warning, once per browser and addressSelect Continue
Unable to reach app. Please try again. when the dialog opensThe agent or the tunnel isn't running, as in Part 10Start both
A seat someone just booked still looks freeThe page shows the seats as they were when it loadedExpected: booking it gets the page again, with the seats as they are now

FAQ​

What's fallbackUrl?​

Another property of the continue answer, next to url. Microsoft's docs describe it as the page to open in a browser tab if a client doesn't support dialogs. Town Hall Seats doesn't set one.

Can the page show a second page, like a wizard?​

Yes. Answer the task/submit with another continue and a different url, and the dialog loads that page. Step 13 did it with the same page and a new address. How to Show the Next Web Page in a Teams Dialog in the Microsoft 365 Agents SDK in C# shows it with two pages.

Does the agent hear about the X?​

No. Closing the dialog with its X sent the agent nothing, as with Cancel. If you need to know whether someone finished, record it when they select your own buttons.

Why not let the agent tell the page the theme?​

Because the task/fetch request's context.theme said default in Teams on the web in the light, dark and high contrast themes alike. The page gets the right value from app.getContext().

Conclusion​

A Teams dialog can show your own web page: the agent answers task/fetch with continue and a url, and Teams loads the page in a frame, as long as the address uses HTTPS, its domain is in the manifest's validDomains, and the page lets Teams frame it. The page connects with TeamsJS's app.initialize(), reads Teams' theme with getContext(), and sends its result with dialog.url.submit, which reaches the agent as task/submit. The agent checks what the page sent, and answers with another page, a message, or nothing, which closes the dialog.

Next: Part 12: Commands, Suggested Actions and Targeted Messages (coming soon). Ways for people to tell your agent what they want, without typing it out.

Additional Resources​