2

这是我的代码。已经一个多月了,我正在尝试在 Outlook 中添加日历,但没有任何效果:(请帮助。该功能AcquireTokenByAuthorizationCodeAsync永远不会完成。并且token.Result始终为空

string authority = ConfigurationManager.AppSettings["authority"];
string clientID = ConfigurationManager.AppSettings["clientID"];
Uri clientAppUri = new Uri(ConfigurationManager.AppSettings["clientAppUri"]);
string serverName = ConfigurationManager.AppSettings["serverName"];

var code = Request.Params["code"];
AuthenticationContext ac = new AuthenticationContext(authority, true);

ClientCredential clcred = new ClientCredential(clientid, secretkey);

//ac = ac.AcquireToken(serverName, clientID, clientAppUri, PromptBehavior.Auto);
//string to = ac.AcquireToken(serverName, clientID, clientAppUri, PromptBehavior.Auto).AccessToken;
var token = ac.AcquireTokenByAuthorizationCodeAsync(code, new Uri("http://localhost:2694/GetAuthCode/Index/"), clcred, resource: "https://graph.microsoft.com/");
string newtoken = token.Result.AccessToken;
ExchangeService exchangeService = new ExchangeService(ExchangeVersion.Exchange2013);
exchangeService.Url = new Uri("https://outlook.office365.com/" + "ews/exchange.asmx");
exchangeService.TraceEnabled = true;
exchangeService.TraceFlags = TraceFlags.All;
exchangeService.Credentials = new OAuthCredentials(token.Result.AccessToken);
exchangeService.FindFolders(WellKnownFolderName.Root, new FolderView(10));

Appointment app = new Appointment(exchangeService);
app.Subject = "";
app.Body = "";
app.Location = "";
app.Start = DateTime.Now;
app.End = DateTime.Now.AddDays(1);
app.Save(SendInvitationsMode.SendToAllAndSaveCopy);
4

1 回答 1

0

当我调用AcquireTokenByAuthorizationCodeAsyncusingresult而不是使用await关键字时,我遇到了这个问题,所有这些代码都在 MVC 的异步控制器中。

如果您处于相同的场景中,您可以通过两种方式解决此问题:

1.始终使用asyncawait如下代码:

public async System.Threading.Tasks.Task<ActionResult> About()
{
    ...
    var result =await ac.AcquireTokenByAuthorizationCodeAsync(code, new Uri("http://localhost:2694/GetAuthCode/Index/"), clcred, resource: "https://graph.microsoft.com/");
    var accessToken = result.AccessToken;
    ...
}

2.使用同步控制器:

public void About()
{
    ...
    var result =ac.AcquireTokenByAuthorizationCodeAsync(code, new Uri("http://localhost:2694/GetAuthCode/Index/"), clcred, resource: "https://graph.microsoft.com/").Result;
    var accessToken = result.AccessToken;
    ...
}
于 2017-07-28T02:19:53.190 回答