
关于
Microsoft 365 Agents .NET SDK。使用 ASP.NET Core 托管、AgentApplication 路由和基于 MSAL 的认证,为 Teams/M365/Copilot Studio 构建多渠道代理。
name: m365-agents-dotnet description: 用于 .NET 的 Microsoft 365 Agents SDK。使用 ASP.NET Core 托管、AgentApplication 路由和基于 MSAL 的认证,为 Teams/M365/Copilot Studio 构建多通道代理。 risk: unknown source: community date_added: '2026-02-27'
Microsoft 365 Agents SDK (.NET)
概述
使用 Microsoft.Agents SDK 配合 ASP.NET Core 托管、代理路由和基于 MSAL 的认证,为 Microsoft 365、Teams 和 Copilot Studio 构建企业代理。
实现前
- 使用 microsoft-docs MCP 验证 AddAgent、AgentApplication 和认证选项的最新 API。
- 在 NuGet 中确认计划使用的 Microsoft.Agents.* 包版本。
安装
dotnet add package Microsoft.Agents.Hosting.AspNetCore
dotnet add package Microsoft.Agents.Authentication.Msal
dotnet add package Microsoft.Agents.Storage
dotnet add package Microsoft.Agents.CopilotStudio.Client
dotnet add package Microsoft.Identity.Client.Extensions.Msal
配置 (appsettings.json)
{
"TokenValidation": {
"Enabled": true,
"Audiences": [
"{{ClientId}}"
],
"TenantId": "{{TenantId}}"
},
"AgentApplication": {
"StartTypingTimer": false,
"RemoveRecipientMention": false,
"NormalizeMentions": false
},
"Connections": {
"ServiceConnection": {
"Settings": {
"AuthType": "ClientSecret",
"ClientId": "{{ClientId}}",
"ClientSecret": "{{ClientSecret}}",
"AuthorityEndpoint": "https://login.microsoftonline.com/{{TenantId}}",
"Scopes": [
"https://api.botframework.com/.default"
]
}
}
},
"ConnectionsMap": [
{
"ServiceUrl": "*",
"Connection": "ServiceConnection"
}
]
}
核心工作流:ASP.NET Core 代理主机
using Microsoft.Agents.Builder;
using Microsoft.Agents.Hosting.AspNetCore;
using Microsoft.Agents.Storage;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddHttpClient();
builder.AddAgentApplicationOptions();
builder.AddAgent<MyAgent>();
builder.Services.AddSingleton<IStorage, MemoryStorage>();
builder.Services.AddControllers();
builder.Services.AddAgentAspNetAuthentication(builder.Configuration);
WebApplication app = builder.Build();
app.UseAuthentication();
app.UseAuthorization();
app.MapGet("/", () => "Microsoft Agents SDK Sample");
var incomingRoute = app.MapPost("/api/messages",
async (HttpRequest request, HttpResponse response, IAgentHttpAdapter adapter, IAgent agent, CancellationToken ct) =>
{
await adapter.ProcessAsync(request, response, agent, ct);
});
if (!app.Environment.IsDevelopment())
{
incomingRoute.RequireAuthorization();
}
else
{
app.Urls.Add("http://localhost:3978");
}
app.Run();
AgentApplication 路由
using Microsoft.Agents.Builder;
using Microsoft.Agents.Builder.App;
using Microsoft.Agents.Builder.State;
using Microsoft.Agents.Core.Models;
using System;
using System.Threading;
using System.Threading.Tasks;
public sealed class MyAgent : AgentApplication
{
public MyAgent(AgentApplicationOptions options) : base(options)
{
OnConversationUpdate(ConversationUpdateEvents.MembersAdded, WelcomeAsync);
OnActivity(ActivityTypes.Message, OnMessageAsync, rank: RouteRank.Last);
OnTurnError(OnTurnErrorAsync);
}
private static async Task WelcomeAsync(ITurnContext turnContext, ITurnState turnState, CancellationToken ct)
{
foreach (ChannelAccount member in turnContext.Activity.MembersAdded)
{
if (member.Id != turnContext.Activity.Recipient.Id)
{
await turnContext.SendActivityAsync("Welcome!", cancellationToken: ct);
}
}
}
private static async Task OnMessageAsync(ITurnContext turnContext, ITurnState turnState, CancellationToken ct)
{
await turnContext.SendActivityAsync(
$"Echo: {turnContext.Activity.Text}", cancellationToken: ct);
}
private static Task OnTurnErrorAsync(ITurnContext turnContext, Exception ex, CancellationToken ct)
{
Console.Error.WriteLine($"Error: {ex.Message}");
return Task.CompletedTask;
}
}
状态管理
using Microsoft.Agents.Builder.State;
// 在 DI 中注册
builder.Services.AddSingleton<IStorage, MemoryStorage>();
// 在代理中使用
public sealed class StatefulAgent : AgentApplication
{
public StatefulAgent(AgentApplicationOptions options) : base(options)
{
OnActivity(ActivityTypes.Message, OnMessageAsync);
}
private static async Task OnMessageAsync(ITurnContext ctx, ITurnState state, CancellationToken ct)
{
var count = state.Conversation.Get<int>("messageCount");
count++;
state.Conversation.Set("messageCount", count);
await ctx.SendActivityAsync($"Message #{count}", cancellationToken: ct);
}
}
Copilot Studio 客户端集成
using Microsoft.Agents.CopilotStudio.Client;
// 将 Copilot Studio 代理作为后端连接
builder.Services.AddCopilotStudioClient(builder.Configuration);
部署通道
| 通道 | 端点 | 说明 | |--------|----------|------| | Teams | /api/messages | 通过 Bot Framework 注册 | | M365 Copilot | /api/messages | 通过 Copilot Studio 发布 | | Web Chat | /api/messages | Direct Line 通道 | | 自定义 | /api/messages | 任何 HTTP 客户端 |
最佳实践
- 生产环境使用持久存储 — 用 Azure Blob/Cosmos 替代 MemoryStorage
- 启用令牌验证 — 生产环境必须验证入站令牌
- 使用 ConnectionsMap — 将服务 URL 映射到正确的认证连接
- 处理轮次错误 — 始终注册 OnTurnError 处理器
- 使用 MSAL 认证 — 企业场景的标准认证方式
兼容工具
Claude CodeCursor
标签
后端开发
