[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill-c3ddb9ad-2365-448d-8ef9-ab00d1284f1f":3,"$ffaGKH-Pi8se5qsW7IVk8D6c7wi1SOJvfw9gixtp9wgQ":43},{"id":4,"title":5,"description":6,"categoryId":7,"moduleId":8,"tags":9,"prompt":10,"icon":11,"source":12,"sourceUrl":13,"authorId":14,"authorName":15,"isPublic":16,"stars":17,"runs":18,"createdAt":19,"updatedAt":19,"module":20,"category":27,"packages":34},"c3ddb9ad-2365-448d-8ef9-ab00d1284f1f","m365-agents-dotnet","Microsoft 365 Agents SDK for .NET。使用 ASP.NET Core 托管、AgentApplication 路由和基于 MSAL 的身份验证构建 Teams\u002FM365\u002FCopilot Studio 的多渠道智能代理。","cat_writing_copywriting","mod_writing","sickn33,writing","---\nname: m365-agents-dotnet\ndescription: Microsoft 365 Agents SDK for .NET. Build multichannel agents for Teams\u002FM365\u002FCopilot Studio with ASP.NET Core hosting, AgentApplication routing, and MSAL-based auth.\nrisk: unknown\nsource: community\ndate_added: '2026-02-27'\n---\n\n# Microsoft 365 Agents SDK (.NET)\n\n## Overview\nBuild enterprise agents for Microsoft 365, Teams, and Copilot Studio using the Microsoft.Agents SDK with ASP.NET Core hosting, agent routing, and MSAL-based authentication.\n\n## Before implementation\n- Use the microsoft-docs MCP to verify the latest APIs for AddAgent, AgentApplication, and authentication options.\n- Confirm package versions in NuGet for the Microsoft.Agents.* packages you plan to use.\n\n## Installation\n\n```bash\ndotnet add package Microsoft.Agents.Hosting.AspNetCore\ndotnet add package Microsoft.Agents.Authentication.Msal\ndotnet add package Microsoft.Agents.Storage\ndotnet add package Microsoft.Agents.CopilotStudio.Client\ndotnet add package Microsoft.Identity.Client.Extensions.Msal\n```\n\n## Configuration (appsettings.json)\n\n```json\n{\n  \"TokenValidation\": {\n    \"Enabled\": true,\n    \"Audiences\": [\n      \"{{ClientId}}\"\n    ],\n    \"TenantId\": \"{{TenantId}}\"\n  },\n  \"AgentApplication\": {\n    \"StartTypingTimer\": false,\n    \"RemoveRecipientMention\": false,\n    \"NormalizeMentions\": false\n  },\n  \"Connections\": {\n    \"ServiceConnection\": {\n      \"Settings\": {\n        \"AuthType\": \"ClientSecret\",\n        \"ClientId\": \"{{ClientId}}\",\n        \"ClientSecret\": \"{{ClientSecret}}\",\n        \"AuthorityEndpoint\": \"https:\u002F\u002Flogin.microsoftonline.com\u002F{{TenantId}}\",\n        \"Scopes\": [\n          \"https:\u002F\u002Fapi.botframework.com\u002F.default\"\n        ]\n      }\n    }\n  },\n  \"ConnectionsMap\": [\n    {\n      \"ServiceUrl\": \"*\",\n      \"Connection\": \"ServiceConnection\"\n    }\n  ],\n  \"CopilotStudioClientSettings\": {\n    \"DirectConnectUrl\": \"\",\n    \"EnvironmentId\": \"\",\n    \"SchemaName\": \"\",\n    \"TenantId\": \"\",\n    \"AppClientId\": \"\",\n    \"AppClientSecret\": \"\"\n  }\n}\n```\n\n## Core Workflow: ASP.NET Core agent host\n\n```csharp\nusing Microsoft.Agents.Builder;\nusing Microsoft.Agents.Hosting.AspNetCore;\nusing Microsoft.Agents.Storage;\nusing Microsoft.AspNetCore.Builder;\nusing Microsoft.AspNetCore.Http;\nusing Microsoft.Extensions.DependencyInjection;\nusing Microsoft.Extensions.Hosting;\n\nvar builder = WebApplication.CreateBuilder(args);\n\nbuilder.Services.AddHttpClient();\nbuilder.AddAgentApplicationOptions();\nbuilder.AddAgent\u003CMyAgent>();\nbuilder.Services.AddSingleton\u003CIStorage, MemoryStorage>();\n\nbuilder.Services.AddControllers();\nbuilder.Services.AddAgentAspNetAuthentication(builder.Configuration);\n\nWebApplication app = builder.Build();\n\napp.UseAuthentication();\napp.UseAuthorization();\n\napp.MapGet(\"\u002F\", () => \"Microsoft Agents SDK Sample\");\n\nvar incomingRoute = app.MapPost(\"\u002Fapi\u002Fmessages\",\n    async (HttpRequest request, HttpResponse response, IAgentHttpAdapter adapter, IAgent agent, CancellationToken ct) =>\n    {\n        await adapter.ProcessAsync(request, response, agent, ct);\n    });\n\nif (!app.Environment.IsDevelopment())\n{\n    incomingRoute.RequireAuthorization();\n}\nelse\n{\n    app.Urls.Add(\"http:\u002F\u002Flocalhost:3978\");\n}\n\napp.Run();\n```\n\n## AgentApplication routing\n\n```csharp\nusing Microsoft.Agents.Builder;\nusing Microsoft.Agents.Builder.App;\nusing Microsoft.Agents.Builder.State;\nusing Microsoft.Agents.Core.Models;\nusing System;\nusing System.Threading;\nusing System.Threading.Tasks;\n\npublic sealed class MyAgent : AgentApplication\n{\n    public MyAgent(AgentApplicationOptions options) : base(options)\n    {\n        OnConversationUpdate(ConversationUpdateEvents.MembersAdded, WelcomeAsync);\n        OnActivity(ActivityTypes.Message, OnMessageAsync, rank: RouteRank.Last);\n        OnTurnError(OnTurnErrorAsync);\n    }\n\n    private static async Task WelcomeAsync(ITurnContext turnContext, ITurnState turnState, CancellationToken ct)\n    {\n        foreach (ChannelAccount member in turnContext.Activity.MembersAdded)\n        {\n            if (member.Id != turnContext.Activity.Recipient.Id)\n            {\n                await turnContext.SendActivityAsync(\n                    MessageFactory.Text(\"Welcome to the agent.\"),\n                    ct);\n            }\n        }\n    }\n\n    private static async Task OnMessageAsync(ITurnContext turnContext, ITurnState turnState, CancellationToken ct)\n    {\n        await turnContext.SendActivityAsync(\n            MessageFactory.Text($\"You said: {turnContext.Activity.Text}\"),\n            ct);\n    }\n\n    private static async Task OnTurnErrorAsync(\n        ITurnContext turnContext,\n        ITurnState turnState,\n        Exception exception,\n        CancellationToken ct)\n    {\n        await turnState.Conversation.DeleteStateAsync(turnContext, ct);\n\n        var endOfConversation = Activity.CreateEndOfConversationActivity();\n        endOfConversation.Code = EndOfConversationCodes.Error;\n        endOfConversation.Text = exception.Message;\n        await turnContext.SendActivityAsync(endOfConversation, ct);\n    }\n}\n```\n\n## Copilot Studio direct-to-engine client\n\n### DelegatingHandler for token acquisition (interactive flow)\n\n```csharp\nusing System.Net.Http.Headers;\nusing Microsoft.Agents.CopilotStudio.Client;\nusing Microsoft.Identity.Client;\n\ninternal sealed class AddTokenHandler : DelegatingHandler\n{\n    private readonly SampleConnectionSettings _settings;\n\n    public AddTokenHandler(SampleConnectionSettings settings) : base(new HttpClientHandler())\n    {\n        _settings = settings;\n    }\n\n    protected override async Task\u003CHttpResponseMessage> SendAsync(\n        HttpRequestMessage request,\n        CancellationToken cancellationToken)\n    {\n        if (request.Headers.Authorization is null)\n        {\n            string[] scopes = [CopilotClient.ScopeFromSettings(_settings)];\n\n            IPublicClientApplication app = PublicClientApplicationBuilder\n                .Create(_settings.AppClientId)\n                .WithAuthority(AadAuthorityAudience.AzureAdMyOrg)\n                .WithTenantId(_settings.TenantId)\n                .WithRedirectUri(\"http:\u002F\u002Flocalhost\")\n                .Build();\n\n            AuthenticationResult authResponse;\n            try\n            {\n                var account = (await app.GetAccountsAsync()).FirstOrDefault();\n                authResponse = await app.AcquireTokenSilent(scopes, account).ExecuteAsync(cancellationToken);\n            }\n            catch (MsalUiRequiredException)\n            {\n                authResponse = await app.AcquireTokenInteractive(scopes).ExecuteAsync(cancellationToken);\n            }\n\n            request.Headers.Authorization = new AuthenticationHeaderValue(\"Bearer\", authResponse.AccessToken);\n        }\n\n        return await base.SendAsync(request, cancellationToken);\n    }\n}\n```\n\n### Console host with CopilotClient\n\n```csharp\nusing Microsoft.Agents.CopilotStudio.Client;\nusing Microsoft.Extensions.DependencyInjection;\nusing Microsoft.Extensions.Hosting;\n\nHostApplicationBuilder builder = Host.CreateApplicationBuilder(args);\n\nvar settings = new SampleConnectionSettings(\n    builder.Configuration.GetSection(\"CopilotStudioClientSettings\"));\n\nbuilder.Services.AddHttpClient(\"mcs\").ConfigurePrimaryHttpMessageHandler(() =>\n{\n    return new AddTokenHandler(settings);\n});\n\nbuilder.Services\n    .AddSingleton(settings)\n    .AddTransient\u003CCopilotClient>(sp =>\n    {\n        var logger = sp.GetRequiredService\u003CILoggerFactory>().CreateLogger\u003CCopilotClient>();\n        return new CopilotClient(settings, sp.GetRequiredService\u003CIHttpClientFactory>(), logger, \"mcs\");\n    });\n\nIHost host = builder.Build();\nvar client = host.Services.GetRequiredService\u003CCopilotClient>();\n\nawait foreach (var activity in client.StartConversationAsync(emitStartConversationEvent: true))\n{\n    Console.WriteLine(activity.Type);\n}\n\nawait foreach (var activity in client.AskQuestionAsync(\"Hello!\", null))\n{\n    Console.WriteLine(activity.Type);\n}\n```\n\n## Best Practices\n\n1. Use AgentApplication subclasses to centralize routing and error handling.\n2. Use MemoryStorage only for development; use persisted storage in production.\n3. Enable TokenValidation in production and require authorization on \u002Fapi\u002Fmessages.\n4. Keep auth secrets in configuration providers (Key Vault, managed identity, env vars).\n5. Reuse HttpClient from IHttpClientFactory and cache MSAL tokens.\n6. Prefer async handlers and pass CancellationToken to SDK calls.\n\n## Reference Files\n\n| File | Contents |\n| --- | --- |\n| references\u002Facceptance-criteria.md | Import paths, hosting pipeline, Copilot Studio client patterns, anti-patterns |\n\n## Reference Links\n\n| Resource | URL |\n| --- | --- |\n| Microsoft 365 Agents SDK | https:\u002F\u002Flearn.microsoft.com\u002Fen-us\u002Fmicrosoft-365\u002Fagents-sdk\u002F |\n| AddAgent API | https:\u002F\u002Flearn.microsoft.com\u002Fen-us\u002Fdotnet\u002Fapi\u002Fmicrosoft.agents.hosting.aspnetcore.servicecollectionextensions.addagent?view=m365-agents-sdk |\n| AgentApplication API | https:\u002F\u002Flearn.microsoft.com\u002Fen-us\u002Fdotnet\u002Fapi\u002Fmicrosoft.agents.builder.app.agentapplication?view=m365-agents-sdk |\n| Auth configuration options | https:\u002F\u002Flearn.microsoft.com\u002Fen-us\u002Fmicrosoft-365\u002Fagents-sdk\u002Fmicrosoft-authentication-library-configuration-options |\n| Copilot Studio integration | https:\u002F\u002Flearn.microsoft.com\u002Fen-us\u002Fmicrosoft-365\u002Fagents-sdk\u002Fintegrate-with-mcs |\n| GitHub samples | https:\u002F\u002Fgithub.com\u002Fmicrosoft\u002Fagents |\n\n## When to Use\nThis skill is applicable to execute the workflow or actions described in the overview.\n\n## Limitations\n- Use this skill only when the task clearly matches the scope described above.\n- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.\n- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.\n","","imported","https:\u002F\u002Fgithub.com\u002Fsickn33\u002Fantigravity-awesome-skills","user_system_seed","SkillOPIC",true,83,1692,"2026-05-16 13:27:17",{"id":8,"name":21,"slug":22,"icon":23,"description":24,"sort":25,"createdAt":26},"写作研究","writing","mdi-pencil-outline","从学术写作到创意文案，让 AI 成为你的专属写作助手",1,"2026-05-16 12:53:40",{"id":7,"name":28,"slug":29,"icon":30,"description":31,"moduleId":8,"sort":32,"skillCount":33,"createdAt":26},"文案策划","copywriting","mdi-comment-text-outline","广告文案、品牌故事、Slogan",4,72,[35],{"id":36,"skillId":4,"version":37,"fileName":38,"fileSize":39,"filePath":40,"fileHash":41,"manifest":42,"createdAt":19},"2e60ea37-2291-4038-bbea-4f96421fe7af","1.0.0","m365-agents-dotnet.zip",3326,"uploads\u002Fskills\u002Fc3ddb9ad-2365-448d-8ef9-ab00d1284f1f\u002Fm365-agents-dotnet.zip","a501ce7919c6cf5babf649b124ea43ecc0635d74df83bfd628016850ca58553e","[{\"path\":\"SKILL.md\",\"isDirectory\":false,\"size\":9710}]",{"code":44,"message":45,"data":46},200,"success",{"items":47,"stats":48,"page":51},[],{"averageRating":49,"totalRatings":49,"ratingCounts":50},0,[49,49,49,49,49],{"limit":52,"offset":49,"hasMore":53,"nextOffset":52,"ratedOnly":16},15,false]