Search code examples
c#asp.net-corepostmicrosoft-graph-apihttpresponse

Get Response Header data from Post Call


I'm calling a Microsoft API to create a printer however I need a way to get the response header where the information about the post is.

I'm following this guide https://learn.microsoft.com/en-us/graph/api/printer-create?view=graph-rest-beta&tabs=csharp but not sure how to extract the response from the call as I can not assign a variable to the call.

await graphClient.Print.Printers
    .Create(displayName,manufacturer,model,certificateSigningRequest,physicalDeviceId,hasPhysicalDevice,connectorId)
    .Request()
    .PostAsync();

Operation-Location


Solution

  • You can send HTTP request with the .Net Microsoft Graph client library and read response headers.

    Something like this:

    var requestUrl = graphClient.Print.Printers.Request().RequestUrl;
    var content = "json_content";
    var hrm = new HttpRequestMessage(HttpMethod.Post, requestUrl);
    hrm.Content = new StringContent(content, System.Text.Encoding.UTF8, "aplication/json");
    // Authenticate (add access token) 
    await client.AuthenticationProvider.AuthenticateRequestAsync(hrm);
    // Send the request and get the response.
    var response = await client.HttpProvider.SendAsync(hrm);
    if (!response.IsSuccessStatusCode)
    {
        throw new ServiceException(
            new Error
            {
                Code = response.StatusCode.ToString(),
                Message = await response.Content.ReadAsStringAsync()
            });
    }     
    else
    {
        // read header values
        var headerValues = response.Headers.GetValues("Operation-Location");
    }
    

    Example of the request body:

    {
      "displayName": "Test Printer",
      "manufacturer": "Test Printer Manufacturer",
      "model": "Test Printer Model",
      "physicalDeviceId": null,
      "hasPhysicalDevice": false,
      "certificateSigningRequest": { 
        "content": "{content}",
        "transportKey": "{sampleTransportKey}"
      },
      "connectorId": null
    }
    

    Documentation