2017-09-26 1 views
1

안녕 모두 로그인 컨트롤러에서 사용자 데이터 저장소에 일부 데이터를 저장하려고합니다.활동없이 등록되지 않은 localhost 봇에 대한 StateClient를 통한 사용자 데이터 액세스

[HttpGet, Route("api/{channelId}/{userId}/authorize")] 
public async System.Threading.Tasks.Task<HttpResponseMessage> Authorize(string channelId, string userId, string code) 
{ 
    string protocalAndDomain = HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority); 

    AuthenticationContext ac = new AuthenticationContext(Constants.AD_AUTH_CONTEXT); 
    ClientCredential cc = new ClientCredential(Constants.AD_CLIENT_ID, Constants.AD_CLIENT_SECRET); 
    AuthenticationResult ar = await ac.AcquireTokenByAuthorizationCodeAsync(code, new Uri(protocalAndDomain + "/api/" + channelId + "/" + userId + "/authorize"), cc); 
    MicrosoftAppCredentials.TrustServiceUrl(protocalAndDomain, DateTime.Now.AddHours(1)); 

    if (!String.IsNullOrEmpty(ar.AccessToken)) 
    { 
     // Store access token & User Id to bot state 
     //var botCred = new MicrosoftAppCredentials(Constants.MS_APP_ID, Constants.MS_APP_PASSWORD); 
     //https://state.botframework.com 

     using (var sc = new StateClient(new Uri("http://localhost:3979/"))) 
      if (sc != null) 
      { 
       var botData = new BotData(data: null, eTag: "*"); 
       botData.SetProperty("accessToken", ar.AccessToken); 
       botData.SetProperty("userEmail", ar.UserInfo.DisplayableId); 

       //i get a 401 response here 
       await sc.BotState.SetUserDataAsync(channelId, userId, botData); 
      } 


     var response = Request.CreateResponse(HttpStatusCode.Moved); 
     response.Headers.Location = new Uri("/loggedin.html", UriKind.Relative); 
     return response; 

    } 
    else 
     return Request.CreateResponse(HttpStatusCode.Unauthorized); 
} 

난 당신이 봇 상태에 액세스 할 수 APPID appPassword를 사용할 수있는 곳에서 예를 본 적이 있지만 봇이 azuer 응용 프로그램 포털에 regested/출판 될 때까지 나의 이해에 사람들은 사용할 수 없습니다하는 내가 현재 할 수 없습니다.

또는 다시 액세스 할 수없는 활동을 통해 액세스 할 수 있습니다.

사실 이것은 내 계획이 결국 Azure 테이블 스토리지에 사용자 데이터를 저장하는 임시 솔루션이지만, 나는 임시적인 솔루션을 원합니다. 로컬 텍스트 파일에 사전을 직렬화 및 비 직렬화하는 것을 고려하고 있지만, 지금은 과도한 것처럼 보일뿐 아니라 하늘에 등록 된 내 앱을 사용하지 않고도 사용자 데이터에 로컬로 저장할 수 없다는 것은 어리석은 것처럼 보입니다.

모든 도움을 많이 받으실 수 있습니다. 이 라인으로

답변

0

:

var sc = new StateClient(new Uri("http://localhost:3979/")) 

당신은 http://localhost:3979/에서 상태 서비스를 사용하는 BotBuilder을 지시하지만 어떤 상태 서비스는 엔드 포인트에 존재하지 않는다.

protected void Application_Start() 
{ 
    Conversation.UpdateContainer(
     builder => 
      { 
       builder.RegisterModule(new AzureModule(Assembly.GetExecutingAssembly())); 

       var store = new InMemoryDataStore(); // volatile in-memory store 

       builder.Register(c => store) 
        .Keyed<IBotDataStore<BotData>>(AzureModule.Key_DataStore) 
        .AsSelf() 
        .SingleInstance(); 


      }); 

    GlobalConfiguration.Configure(WebApiConfig.Register); 
} 

주 : 당신은 당신이 푸른 표 스토리지를 추가 할 때까지 임시 솔루션을 원한다면

, 당신은 InMemoryDataStore을 사용할 수 있습니다 이것은 InMemoryDataStore되면 https://www.nuget.org/packages/Microsoft.Bot.Builder.Azure/

패키지 nuget 애저 확장이 필요 가 등록 된 경우 다음과 같은 형식으로 액세스 할 수 있습니다.

var message = new Activity() 
       { 
        ChannelId = ChannelIds.Directline, 
        From = new ChannelAccount(userId, userName), 
        Recipient = new ChannelAccount(botId, botName), 
        Conversation = new ConversationAccount(id: conversationId), 
        ServiceUrl = serviceUrl 
       }.AsMessageActivity(); 

using (var scope = DialogModule.BeginLifetimeScope(Conversation.Container, message)) 
{ 
    var botDataStore = scope.Resolve<IBotDataStore<BotData>>(); 
    var key = new AddressKey() 
    { 
     BotId = message.Recipient.Id, 
     ChannelId = message.ChannelId, 
     UserId = message.From.Id, 
     ConversationId = message.Conversation.Id, 
     ServiceUrl = message.ServiceUrl 
    }; 
    var userData = await botDataStore.LoadAsync(key, BotStoreType.BotUserData, CancellationToken.None); 

    userData.SetProperty("key 1", "value1"); 
    userData.SetProperty("key 2", "value2"); 

    await botDataStore.SaveAsync(key, BotStoreType.BotUserData, userData, CancellationToken.None); 
    await botDataStore.FlushAsync(key, CancellationToken.None); 
} 
관련 문제