[英]Calling and displaying the results of List memberOf in Microsft Graph
我正在嘗試在我的ASP.NET MVC
應用程序中顯示用戶所屬的 Office 365 組。 在我的UsersController
,我創建了一個 Microsoft Graph 客戶端,並向 Graph 服務發出請求以調用 MemberOf API。 問題是,當我想將控制器的結果顯示到視圖中時,我不明白應該在我的模型中調用哪個 Microsoft Graph 命名空間來顯示組名稱、描述和我在調用時得到的其他響應:獲取https://graph.microsoft.com/v1.0/me/memberOf 。
我遵循了關於 List memberOf ( https://docs.microsoft.com/en-us/graph/api/user-list-memberof?view=graph-rest-1.0&tabs=http ) 的 Microsoft Graph 文檔,我包含了以下內容我的用戶控制器中的代碼:
public async Task<ActionResult> MyGroups()
{
string token = await GetAccessToken();
if (string.IsNullOrEmpty(token))
{
// If there's no token in the session, redirect to Home
return Redirect("/");
}
GraphServiceClient client = new GraphServiceClient(
new DelegateAuthenticationProvider(
(requestMessage) =>
{
requestMessage.Headers.Authorization =
new AuthenticationHeaderValue("Bearer", token);
return Task.FromResult(0);
}));
try
{
var memberOf = await client.Me.MemberOf.Request()
.GetAsync();
return View(memberOf);
}
catch (ServiceException ex)
{
return RedirectToAction("Error", "Home", new { message = "ERROR retrieving events", debug = ex.Message });
}
}
然后,在我的 MyGroups 視圖中,我正在訪問 Microsoft.Graph.Group 命名空間,但在運行項目時出現錯誤。
這是視圖代碼:
@model Microsoft.Graph.Group
@{
ViewBag.Title = "My info";
}
<h2>My groups</h2>
<table class="table">
<tr>
<th>
DisplayName
</th>
<th>
GroupTypes
</th>
</tr>
<tr>
<td>
@this.Model.DisplayName
</td>
<td>
@this.Model.Description
</td>
</tr>
這是我在瀏覽器上得到的錯誤:
傳遞到字典中的模型項的類型為“Microsoft.Graph.UserMemberOfCollectionWithReferencesPage”,但此字典需要類型為“Microsoft.Graph.Group”的模型項。
有人可以告訴我應該使用正確的 Microsoft Graph 命名空間來顯示 me/memberOf 的結果嗎?
您是否打算展示所有組? 如果是這樣,您的模型應該是IEnumerable<Microsoft.Graph.Group>
。 你的<tr>
標簽包含在一個循環中。
@foreach (var item in Model)
{
<tr>
<td>
@item.displayName
</td>
<td>
@item.description
</td>
</tr>
}
(代碼來自內存,因此可能無法編譯。)
在控制器中,您需要傳遞 CurrentPage(或更新您的代碼以讀取所有頁面):
return View(memberOf.CurrentPage);
https://github.com/microsoftgraph/msgraph-sdk-dotnet/blob/dev/docs/collections.md
我設法顯示用戶所屬的組,在 UsersController 中使用以下代碼:
var memberOf = await client.Me.MemberOf.Request().GetAsync();
List<Group> groups = memberOf.OfType<Microsoft.Graph.Group>().ToList();
return View(groups);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.