从 C# 调用图形 API 时出现不可接受的错误

Bax*_*orr -1 c# asp.net-core microsoft-graph-sdks microsoft-graph-api

嘿伙计们,我正在尝试获取租户中所有房间的列表,但我收到一个错误,我看不到解决方案。我的图形服务客户端似乎是正确的,因为我可以毫无问题地获取所有用户的列表,但获取所有房间失败并出现未知错误。

我想要复制的内容:https://learn.microsoft.com/en-us/graph/api/place-list ?view=graph-rest-1.0&tabs=csharp#request

创建图形客户端并尝试从地方获取房间列表

public GraphServiceClient CreateGraphClient()
{
    var scopes = new[] { "https://graph.microsoft.com/.default" };
    var options = new TokenCredentialOptions
    {
        AuthorityHost = AzureAuthorityHosts.AzurePublicCloud
    };

    // https://learn.microsoft.com/dotnet/api/azure.identity.clientsecretcredential
    var clientSecretCredential = new ClientSecretCredential(
        tenantId, clientId, clientSecret, options);

    return new GraphServiceClient(clientSecretCredential, scopes);
}

public async Task<List<string>> GetRoomsAsync()
{
    var rooms = await graphClient.Places.Request().GetAsync();

    var roomsList = new List<string>();

    foreach (var room in rooms)
    {
        Console.WriteLine(room.DisplayName);
        roomsList.Add(room.DisplayName);
    }
    return roomsList;
}
Run Code Online (Sandbox Code Playgroud)

当试图获取用户时,同样的事情也会发生。

    public async Task<List<string>> GetUsersAsync()
    {
        var users = await graphClient.Users.Request().GetAsync();
        var user_list = new List<string>();

        foreach (var user in users)
        {
            user_list.Add(user.DisplayName);
        }

        return user_list;
    }
Run Code Online (Sandbox Code Playgroud)

我的 Azure 广告权限

Azure 广告应用权限

错误代码:

      An unhandled exception has occurred while executing the request.
      Status Code: NotAcceptable
      Microsoft.Graph.ServiceException: Code: UnknownError
      Inner error:
        AdditionalData:
        date: 2022-09-11T12:06:02
        request-id: 1d5d8c56-235c-452d-aa2c-9d71cbf2d7a9
        client-request-id: 1d5d8c56-235c-452d-aa2c-9d71cbf2d7a9
      ClientRequestId: 1d5d8c56-235c-452d-aa2c-9d71cbf2d7a9

         at Microsoft.Graph.HttpProvider.SendAsync(HttpRequestMessage request, HttpCompletionOption completionOption, CancellationToken cancellationToken)
         at Microsoft.Graph.BaseRequest.SendRequestAsync(Object serializableObject, CancellationToken cancellationToken, HttpCompletionOption completionOption)
         at Microsoft.Graph.BaseRequest.SendAsync[T](Object serializableObject, CancellationToken cancellationToken, HttpCompletionOption completionOption)
         at Microsoft.Graph.GraphServicePlacesCollectionRequest.GetAsync(CancellationToken cancellationToken)
         at PicoWebAPI.Controllers.MeetingsController.Get() in C:\Users\Blue\source\repos\MeetingRoomBooking\PicoWebAPI\Controllers\MeetingsController.cs:line 25
         at lambda_method5(Closure , Object )
         at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.AwaitableObjectResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
         at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeActionMethodAsync>g__Awaited|12_0(ControllerActionInvoker invoker, ValueTask`1 actionResultValueTask)
         at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeNextActionFilterAsync>g__Awaited|10_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
         at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context)
         at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
         at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeInnerFilterAsync>g__Awaited|13_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
         at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|20_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
         at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
         at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
         at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
         at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
         at Swashbuckle.AspNetCore.SwaggerUI.SwaggerUIMiddleware.Invoke(HttpContext httpContext)
         at Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.Invoke(HttpContext httpContext, ISwaggerProvider swaggerProvider)
         at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
Run Code Online (Sandbox Code Playgroud)

Tin*_*ang 6

Let's see the api response via http request, and we can also see the graph api return the same UnknownError as graph SDK:

在此输入图像描述 在此输入图像描述

So in this scenario, request https://graph.microsoft.com/v1.0/places equals to SDK await graphClient.Places.Request().GetAsync(); which should met this error. And this is because Graph SDK does not currently support filtering by derived types which is a known issue. A similar issue here.

And this is the workaround and it worked for me:

var graphClient = new GraphServiceClient(clientSecretCredential, scopes);
var roomUrl = graphClient.Places.AppendSegmentToRequestUrl("microsoft.graph.room");
var placesRequest = await new GraphServicePlacesCollectionRequest(roomUrl, graphClient, null).GetAsync();
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

  • 这有效。感谢您的回答并展示了整个过程,现在我知道如果再次遇到该问题如何处理。你是最好的! (3认同)