microsoft/teams.net
Publicmirrored fromhttps://github.com/microsoft/teams.netAvailable
teams.net/Libraries/Microsoft.Teams.Plugins/Microsoft.Teams.Plugins.AspNetCore.BotBuilder/Controllers
Libraries/Microsoft.Teams.Plugins/Microsoft.Teams.Plugins.AspNetCore.BotBuilder/Controllers/MessageController.cs
69lines · modecode
| 1 | // Copyright (c) Microsoft Corporation. All rights reserved. |
| 2 | // Licensed under the MIT License. |
| 3 | |
| 4 | using System.Text.Json; |
| 5 | |
| 6 | using Microsoft.AspNetCore.Http; |
| 7 | using Microsoft.AspNetCore.Mvc; |
| 8 | using Microsoft.Bot.Builder; |
| 9 | using Microsoft.Bot.Builder.Integration.AspNet.Core; |
| 10 | using Microsoft.Extensions.Hosting; |
| 11 | using Microsoft.Teams.Api.Activities; |
| 12 | using Microsoft.Teams.Api.Auth; |
| 13 | |
| 14 | namespace Microsoft.Teams.Plugins.AspNetCore.BotBuilder |
| 15 | { |
| 16 | [ApiController] |
| 17 | public class MessageController : ControllerBase |
| 18 | { |
| 19 | private readonly IBotFrameworkHttpAdapter _adapter; |
| 20 | private readonly IBot _bot; |
| 21 | |
| 22 | private readonly AspNetCorePlugin _plugin; |
| 23 | |
| 24 | private readonly IHostApplicationLifetime _lifetime; |
| 25 | |
| 26 | public MessageController(IBotFrameworkHttpAdapter adapter, IBot bot, AspNetCorePlugin plugin, IHostApplicationLifetime lifetime) |
| 27 | { |
| 28 | _plugin = plugin; |
| 29 | _lifetime = lifetime; |
| 30 | _adapter = adapter; |
| 31 | _bot = bot; |
| 32 | } |
| 33 | |
| 34 | [HttpPost("/api/messages")] |
| 35 | public async Task<IResult> PostAsync() |
| 36 | { |
| 37 | HttpContext.Request.EnableBuffering(); |
| 38 | var body = await new StreamReader(Request.Body).ReadToEndAsync(); |
| 39 | Activity? activity = JsonSerializer.Deserialize<Activity>(body); |
| 40 | HttpContext.Request.Body.Position = 0; |
| 41 | |
| 42 | if (activity == null) |
| 43 | { |
| 44 | return Results.BadRequest("Missing activity"); |
| 45 | } |
| 46 | |
| 47 | // Delegate the processing of the HTTP POST to the adapter. |
| 48 | // The adapter will invoke the bot. |
| 49 | await _adapter.ProcessAsync(HttpContext.Request, HttpContext.Response, _bot); |
| 50 | |
| 51 | if (Response.HasStarted) |
| 52 | { |
| 53 | return Results.Empty; |
| 54 | } |
| 55 | |
| 56 | // Fallback logic |
| 57 | var authHeader = HttpContext.Request.Headers.Authorization.FirstOrDefault() ?? throw new UnauthorizedAccessException(); |
| 58 | var token = new JsonWebToken(authHeader.Replace("Bearer ", "")); |
| 59 | var res = await _plugin.Do(new() |
| 60 | { |
| 61 | Token = token, |
| 62 | Activity = activity, |
| 63 | Services = HttpContext.RequestServices |
| 64 | }, _lifetime.ApplicationStopping); |
| 65 | |
| 66 | return Results.Json(res.Body, statusCode: (int)res.Status); |
| 67 | } |
| 68 | } |
| 69 | } |