从 Post 调用中获取响应 Header 数据

Get Response Header data from Post Call

我正在调用 Microsoft API 创建打印机,但是我需要一种方法来获取响应 header,其中包含有关 post 的信息。

我正在按照本指南进行操作 https://docs.microsoft.com/en-us/graph/api/printer-create?view=graph-rest-beta&tabs=csharp,但不确定如何从调用中提取响应,因为我无法为调用分配变量。

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

Operation-Location

您可以使用 .Net Microsoft Graph 客户端库发送 HTTP 请求并读取响应 headers。

像这样:

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");
}

请求示例body:

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

Documentation