我創建了一個 .net 網站應用程式,并添加了與下面的參考視頻相同的 dll 和代碼。
https://www.youtube.com/watch?v=KNJUrCHv6no&list=PLWZJrkeLOrbZ8Gl8zsxUuXTkmytyiEGSh&index=5
我創建了一個免費訂閱的免費 Microsoft 帳戶,我的 id 像 ([email protected]),我在 Azure 中注冊了我的應用程式,與https://www.youtube.com/watch?v=k7nnvdNgfOE&list=PLWZJrkeLOrbZ8Gl8zsxUuXTkmytyiEGSh&index=4相同 視頻。
但它不適合我。request.GetAsync().Result 需要更多時間并顯示請求超時問題。我在下面添加了我的代碼。請建議。
默認.aspx
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.Identity.Client;
using Microsoft.Graph;
using Microsoft.Extensions.Configuration;
using Helpers;
using System.Security;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
var config = LoadAppSettings();
if (config == null)
{
iserror.Text = "config error";
return;
}
try
{
var userName = ReadUsername();
var userPassword = ReadPassword();
var client = GetAuthenticatedGraphClient(config, userName, userPassword);
var request = client.Me.Drive.Root.Children.Request();
var results = request.GetAsync().Result;
foreach (var file in results)
{
}
}
catch { iserror.Text = "config file exist. azure error"; }
}
private static SecureString ReadPassword()
{
var securePassword = "xxxxxxx";
SecureString password = new SecureString();
foreach (char c in securePassword)
password.AppendChar(c);
return password;
}
private static string ReadUsername()
{
string username;
username = "[email protected]";
return username;
}
private static GraphServiceClient GetAuthenticatedGraphClient(IConfigurationRoot config, string userName, SecureString userPassword)
{
var authenticationProvider = CreateAuthorizationProvider(config, userName, userPassword);
var graphClient = new GraphServiceClient(authenticationProvider);
return graphClient;
}
private static IAuthenticationProvider CreateAuthorizationProvider(IConfigurationRoot config, string userName, SecureString userPassword)
{
var clientId = config["applicationId"];
var authority = "https://login.microsoftonline.com/" config["tenantId"] "/v2.0";
List<string> scopes = new List<string>();
scopes.Add("User.Read");
scopes.Add("Files.Read");
var cca = PublicClientApplicationBuilder.Create(clientId)
.WithAuthority(authority)
.Build();
return MsalAuthenticationProvider.GetInstance(cca, scopes.ToArray(), userName, userPassword);
}
private static IConfigurationRoot LoadAppSettings()
{
try
{
string asas = HttpContext.Current.Server.MapPath("");
var config = new ConfigurationBuilder()
.SetBasePath(asas)
.AddJsonFile("appsettings.json", false, true)
.Build();
if (string.IsNullOrEmpty(config["applicationId"]) ||
string.IsNullOrEmpty(config["tenantId"]))
{
return null;
}
return config;
}
catch (System.IO.FileNotFoundException)
{
return null;
}
}
}
MsalAuthenticationProvider.cs
using System.Net.Http;
using System.Net.Http.Headers;
using System.Security;
using System.Threading.Tasks;
using Microsoft.Identity.Client;
using Microsoft.Graph;
namespace Helpers
{
public class MsalAuthenticationProvider : IAuthenticationProvider
{
private static MsalAuthenticationProvider _singleton;
private IPublicClientApplication _clientApplication;
private string[] _scopes;
private string _username;
private SecureString _password;
private string _userId;
private MsalAuthenticationProvider(IPublicClientApplication clientApplication, string[] scopes, string username, SecureString password)
{
_clientApplication = clientApplication;
_scopes = scopes;
_username = username;
_password = password;
_userId = null;
}
public static MsalAuthenticationProvider GetInstance(IPublicClientApplication clientApplication, string[] scopes, string username, SecureString password)
{
if (_singleton == null)
{
_singleton = new MsalAuthenticationProvider(clientApplication, scopes, username, password);
}
return _singleton;
}
public async Task AuthenticateRequestAsync(HttpRequestMessage request)
{
var accessToken = await GetTokenAsync();
request.Headers.Authorization = new AuthenticationHeaderValue("bearer", accessToken);
}
public async Task<string> GetTokenAsync()
{
if (!string.IsNullOrEmpty(_userId))
{
try
{
var account = await _clientApplication.GetAccountAsync(_userId);
if (account != null)
{
var silentResult = await _clientApplication.AcquireTokenSilent(_scopes, account).ExecuteAsync();
return silentResult.AccessToken;
}
}
catch (MsalUiRequiredException) { }
}
var result = await _clientApplication.AcquireTokenByUsernamePassword(_scopes, _username, _password).ExecuteAsync();
_userId = result.Account.HomeAccountId.Identifier;
return result.AccessToken;
}
}
}
應用設定.json *
{
"tenantId": "xxxx",
"applicationId": "xxxx"
}
uj5u.com熱心網友回復:
- 看起來您遇到了
deadlock異步方法嘗試繼續執行緒的標準情況,即blocked by the call to Result. 嘗試使用 async Task 測驗方法而不是 void 。
注意:尤其是在用戶互動中,應該小心使用
.Result主執行緒上的呼叫來阻止阻塞,因為這種型別的呼叫可能會鎖定您的應用程式以進行進一步的用戶互動。
嘗試避免在呼叫中使用 Result。
var results = await request.GetAsync();并做
check if you need to add async to all the methods。還要檢查這個c# - 使用 Microsoft Graph 查詢驅動器專案時 -相關的堆疊溢位。
此外,如果以上沒有解決,請嘗試
set the Timeout更高的值示例:到一小時:
graphServiceClient.HttpProvider.OverallTimeout = TimeSpan.FromHours(1);
請檢查以下有用的參考資料:
- c# - 'await' 有效,但呼叫 task.Result 掛起/死鎖 - 代碼日志
- 如何在控制臺應用程式中訪問 Microsoft Graph API (c-sharpcorner.com)
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/496923.html
標籤:网 天蓝色活动目录 微软图形 API 天蓝色广告图 API office365api
上一篇:如何從AAD組中獲取組成員資格
