Microsoft Graph 오류 응답-JSON에서 HTTP 상태 코드 및 내부 오류 코드를 추출하는 방법은 무엇입니까?

OJB1

현재 .NET Core 3.1 앱에서 MS Graph .NET Core SDK 클라이언트를 테스트하고 있습니다. 목적은 Azure B2C AD에서 사용자 업데이트 / 변경 / 가져 오기를 수행하는 자체 로컬 웹 API 사용자 서비스를 제공하는 것입니다.

내 의도 한 솔루션에는 REST를 직접 사용하여 Azure Graph API를 호출하는 것과 달리 API 명령을 내 사용자 서비스 SDK 클라이언트에 호출하는 다양한 HTTP 클라이언트 마이크로 서비스가 있습니다.

내 사용자 서비스 앱에서 Azure로 전송되는 실제 SDK 명령에 대한 리포지토리 / 인터페이스 접근 방식을 사용하여 깔끔하게 유지하려고합니다. 이 동일한 사용자 서비스 앱은 자체 웹 API를 사용하여 데이터를 로컬 HTTP 클라이언트로 반환합니다. 이 사용자 서비스 앱이 중간 효과라고 상상해보십시오.

환경을 요약 한 아래 이미지 :

여기에 이미지 설명 입력

이것의 목적은 그래프 서비스와 함께 사용되는 기능을 변경하거나 추가 할 때 작업을 줄이는 것입니다. 즉, 내 로컬 앱에서 통신에 약간의 표준화를 제공하고 더 나은 문제 분리를 촉진하는 것입니다. 또한 MS가 Graph API를 변경하면 모든 HTTP 클라이언트 앱에서 코드를 변경하는 대신 사용자 서비스 앱만 업데이트합니다. 이해가 되길 바랍니다.

어쨌든, 이제 요점! 내 질문에 대한 이유 :

(bear with me here, I'm new to REST and using Interfaces)

Any errors encountered between the Graph SDK Client and the Graph Service API in Azure will be logged within the my user service app i.e. the extensive json error details i will capture at the first opportunity, HOWEVER I simply don't need to pass this level of detail back to all my local calling HTTP Clients.

What I'm trying to achieve is a means of identifying/capturing any HTTP Status code errors that were encountered between the SDK Client and the Graph Service, along with perhaps some basic details of the error i.e a short description and only pass these lower level details back to my local HTTP Clients i.e, keep things clean.

I'm struggling with knowing how to do this in my code, especially given the fact that i'm using an interface at the same time is making it more complex. The MS docs does give info on the list of expected error codes to be had from using the graph service, but there is no examples that explains how to process this information in order to pass the relevant (but lighter version of the info) back to another source.

Example scenario:

  1. Local HTTP Clients call [HttpGet] GetUserById to my user service Web API
  2. My Web API then uses the Graph SDK Client to reach out to Azure B2C, fetch the data and return.
  3. My WEB API should then inspect the info received, if a user if found then great, return the user to my calling HTTP Client.
  4. IF the user was not found, or perhaps a bad request was made (missing attributes / wrong user id etc) then I need to inspect the HTTP Status error code received and pass this same error code back to my calling HTTP Client, at the same time, rather than passing back the extensive json error details received from Graph Service, I just to want pass back a more simplified message, such as user not found.
  5. The logical approach for the simplified message would be to utilize the already baked in codes messages provided by the Graph Service:

Like below: The "code" attribute is enough to explain the situation to any calling HTTP Client, if I need to investigate further then I would inspect the logs:

 {
   "error": {
     "code": "invalidRange",
     "message": "Uploaded fragment overlaps with existing data.",
     "innerError": {
       "requestId": "request-id",
       "date": "date-time"
     }
   }
 }

SDK를 통한 Graph Service 호출에서 수신 된 HTTP 상태 코드를 추출하는 방법과 본문의 json 오류 메시지에서 단일 속성을 가져온 다음이 축소 / 단순화를 반환하는 방법을 알아낼 수 없습니다. 정보를 내 HTTP 클라이언트에 올 바르고 준수하는 방식으로 되돌립니다. 지금까지 내 프로젝트 코드는 다음과 같습니다.

내 사용자 서비스 웹 API 컨트롤러 :

    [HttpGet("{id}")]
    public async Task<IActionResult> GetUserById(string id)
    {
        try
        {
            var user = await _repository.GetUserByIdAsync(id);

        }
        catch(Exception ex) 
        {
            // What am I catching here? how do I get the HTTP Status Code that 
            was received from the call to the Graph Service in the event of an error?
            // How do i extract the code error key/value from the json received from Graph Service?
        }

        // Finally, how do I return this captured info to the HTTP Client?


        // Ignore this part, not sufficient for my needs.   
        //if (user == null) return BadRequest();
        //if (user != null) return Ok(user);
        //else return NotFound();
    }

내 인터페이스 :

namespace MicrosoftGraph_API.Repository
{
    public interface IGraphClientRepo
    {
        public Task<List<User>> GetAllUsersAsync();

        public Task<User> GetUserByIdAsync(string id); 
    }
}

내 그래프 SDK 클라이언트 클래스 :

public class GraphSDKClientRepo : IGraphClientRepo
{
    public readonly IUserServiceClient _IUserServiceClient;

    public GraphSDKClientRepo(IUserServiceClient userServiceClient)
    {
        _IUserServiceClient = userServiceClient;
    }

    public async Task<User> GetUserByIdAsync(string id)
    {
        var graphClient = _IUserServiceClient.InitializeGraphClient();

        // Get user by object ID
        var result = await graphClient.Users[id]
            .Request()
            .Select(e => new
            {
                e.DisplayName,
                e.Id,
                e.Identities
            })
            .GetAsync();

        return result;
    }
}
마크 라플 뢰르

호출에 오류가 발생하면 SDK에서 ServiceException. 이 클래스에는 찾고있는 속성이 포함됩니다.

/// <summary>
/// The HTTP status code from the response.
/// </summary>
public System.Net.HttpStatusCode StatusCode { get; }

따라서 Graph에 대한 호출은 다음과 같습니다.

public async Task<User> GetUserByIdAsync(string id)
{
    var graphClient = _IUserServiceClient.InitializeGraphClient();

    // Get user by object ID
    try
    {
        return await graphClient
            .Users[id]
            .Request()
            .Select("id,displayName,identities")
            .GetAsync();
    }
    catch (ServiceException)
    {
        throw;
    }
}

그리고 당신은 컨트롤러 코드는 다음과 같습니다.


[HttpGet("{id}")]
public async Task<IActionResult> GetUserById(string id)
{
    try
    {
        return this.Ok(await _repository.GetUserByIdAsync(id));
    }
    catch (ServiceException ex)
    {
        return this.StatusCode(se.StatusCode);
    }
}

HTTP 상태에 따라 예외를 다르게 처리해야하는 경우에도 그렇게 할 수 있습니다.

[HttpGet("{id}")]
public async Task<IActionResult> GetUserById(string id)
{
    try
    {
        return this.Ok(await _repository.GetUserByIdAsync(id));
    }
    catch (ServiceException e) when(e.StatusCode == System.Net.HttpStatusCode.NotFound)
    {
        //
        // Do "Not Found" stuff
        //
        return this.StatusCode(e.StatusCode);
    }
    catch (ServiceException e) when(e.StatusCode == System.Net.HttpStatusCode.BadRequest)
    {
        //
        // Do "Bad Request" stuff
        //
        return this.StatusCode(e.StatusCode);
    }
    catch (ServiceException e)
    {
        return this.StatusCode(e.StatusCode);
    }
}

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

Related 관련 기사

뜨겁다태그

보관