microsoft/teams.net
Publicmirrored from https://github.com/microsoft/teams.netAvailable
Libraries/Microsoft.Teams.Plugins/Microsoft.Teams.Plugins.AspNetCore/Controllers/MessageController.cs
65lines · modecode
| 1 | // Copyright (c) Microsoft Corporation. All rights reserved. |
| 2 | // Licensed under the MIT License. |
| 3 | |
| 4 | using Microsoft.AspNetCore.Authorization; |
| 5 | using Microsoft.AspNetCore.Http; |
| 6 | using Microsoft.AspNetCore.Mvc; |
| 7 | using Microsoft.Extensions.Hosting; |
| 8 | using Microsoft.Teams.Api.Activities; |
| 9 | using Microsoft.Teams.Api.Auth; |
| 10 | |
| 11 | using static Microsoft.Teams.Plugins.AspNetCore.Extensions.HostApplicationBuilderExtensions; |
| 12 | |
| 13 | namespace Microsoft.Teams.Plugins.AspNetCore.Controllers; |
| 14 | |
| 15 | [ApiController] |
| 16 | public class MessageController : ControllerBase |
| 17 | { |
| 18 | private readonly AspNetCorePlugin _plugin; |
| 19 | private readonly IHostApplicationLifetime _lifetime; |
| 20 | |
| 21 | public MessageController(AspNetCorePlugin plugin, IHostApplicationLifetime lifetime) |
| 22 | { |
| 23 | _plugin = plugin; |
| 24 | _lifetime = lifetime; |
| 25 | } |
| 26 | |
| 27 | [HttpPost("/api/messages")] |
| 28 | [Authorize(Policy = TeamsTokenAuthConstants.AuthorizationPolicy)] |
| 29 | public async Task<IResult> OnMessage([FromBody] Activity activity) |
| 30 | { |
| 31 | var authHeader = HttpContext.Request.Headers.Authorization.FirstOrDefault() ?? throw new UnauthorizedAccessException(); |
| 32 | var token = new JsonWebToken(authHeader.Replace("Bearer ", "")); |
| 33 | var data = new Dictionary<string, object?> |
| 34 | { |
| 35 | ["Request.TraceId"] = HttpContext.TraceIdentifier |
| 36 | }; |
| 37 | |
| 38 | foreach (var pair in HttpContext.Items) |
| 39 | { |
| 40 | var key = pair.Key.ToString(); |
| 41 | |
| 42 | if (key is null) continue; |
| 43 | |
| 44 | data[key] = pair.Value; |
| 45 | } |
| 46 | |
| 47 | var res = await _plugin.Do(new() |
| 48 | { |
| 49 | Token = token, |
| 50 | Activity = activity, |
| 51 | Extra = data, |
| 52 | Services = HttpContext.RequestServices |
| 53 | }, _lifetime.ApplicationStopping); |
| 54 | |
| 55 | // convert response metadata to headers |
| 56 | foreach (var (key, value) in res.Meta) |
| 57 | { |
| 58 | var str = value?.ToString(); |
| 59 | if (string.IsNullOrEmpty(str)) continue; |
| 60 | Response.Headers.Append($"X-Teams-{char.ToUpper(key[0]) + key[1..]}", str); |
| 61 | } |
| 62 | |
| 63 | return Results.Json(res.Body, statusCode: (int)res.Status); |
| 64 | } |
| 65 | } |