多租户实施 - 可能的解决方案
将消息端点的路由更改为采用通配符,如下所示:
/// <summary>
/// POST: api/Messages
/// Receive a message from a user and reply to it
/// </summary>
[Route("messages/{*wildcard}")]
public async Task<HttpResponseMessage> Post([FromBody]Activity activity)
{
实现一个多租户机器人身份验证属性,该属性将从最后一个 url 段获取应用程序 ID(或从数据库中获取它的查找)。
例如http://localhost:3979/messages/your-bot-app-id-or-key
[MultiTentantBotAuthentication]
public class MessagesController : ApiController
{
执行
public class MultiTentantBotAuthenticationAttribute : BotAuthentication
{
public override async Task OnAuthorizationAsync(HttpActionContext actionContext, CancellationToken cancellationToken)
{
this.MicrosoftAppId = actionContext.Request.RequestUri.Segments.Last();
await base.OnAuthorizationAsync(actionContext, cancellationToken);
}
}
如果您需要机器人中的代码来了解它在哪个应用程序中运行,您可以通过 userdata 将其传递,如下所示:
/// <summary>
/// POST: api/Messages
/// Receive a message from a user and reply to it
/// </summary>
[Route("messages/{*wildcard}")]
public async Task<HttpResponseMessage> Post([FromBody]Activity activity)
{
var botId = Request.RequestUri.Segments.Last(); // Validate against your database / configuration
try
{
if (activity.Type == ActivityTypes.Message)
{
// https://docs.botframework.com/en-us/csharp/builder/sdkreference/stateapi.html
var stateClient = activity.GetStateClient();
BotData userData = await stateClient.BotState.GetUserDataAsync(activity.ChannelId, activity.From.Id);
userData.SetProperty("ApplicationAccountBotId", botId);
await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);
await Conversation.SendAsync(activity, () => actionDialog);
}
else
{
HandleSystemMessage(activity);
}
}
catch (Exception exception)
{
await logger.ErrorAsync(exception);
}
return Request.CreateResponse(HttpStatusCode.OK);
}
然后,您可以在对话框/机器人代码中访问用户数据。