2017-01-20 7 views
3

Я получаю из нескольких частей содержимого ответа, который принадлежит запросу OAuth пакетного:C# OAuth партия многочастного содержания ответа, как получить все содержимое не как объекты строки

// batchRequest is a HttpRequestMessage, http is an HttpClient 
HttpResponseMessage response = await http.SendAsync(batchRequest); 

Если я прочитал его содержание в полном объеме текст:

string fullResponse = await response.Content.ReadAsStringAsync(); 

Это то, что он содержит:

--batchresponse_e42a30ca-0f3a-4c17-8672-22abc469cd16 
Content-Type: application/http 
Content-Transfer-Encoding: binary 

HTTP/1.1 200 OK 
DataServiceVersion: 3.0; 
Content-Type: application/json;odata=minimalmetadata;streaming=true;charset=utf-8 

{\"odata.metadata\":\"https://graph.windows.net/XXX.onmicrosoft.com/$metadata#directoryObjects/@Element\",\"odata.type\":\"Microsoft.DirectoryServices.User\",\"objectType\":\"User\",\"objectId\":\"5f6851c3-99cc-4a89-936d-4bb44fa78a34\",\"deletionTimestamp\":null,\"accountEnabled\":true,\"signInNames\":[],\"assignedLicenses\":[],\"assignedPlans\":[],\"city\":null,\"companyName\":null,\"country\":null,\"creationType\":null,\"department\":\"NRF\",\"dirSyncEnabled\":null,\"displayName\":\"dummy1 Test\",\"facsimileTelephoneNumber\":null,\"givenName\":\"dummy1\",\"immutableId\":null,\"isCompromised\":null,\"jobTitle\":\"test\",\"lastDirSyncTime\":null,\"mail\":null,\"mailNickname\":\"dummy1test\",\"mobile\":null,\"onPremisesSecurityIdentifier\":null,\"otherMails\":[],\"passwordPolicies\":null,\"passwordProfile\":{\"password\":null,\"forceChangePasswordNextLogin\":true,\"enforceChangePasswordPolicy\":false},\"physicalDeliveryOfficeName\":null,\"postalCode\":null,\"preferredLanguage\":null,\"provisionedPlans\":[],\"provisioningErrors\":[],\"proxyAddresses\":[],\"refreshTokensValidFromDateTime\":\"2016-12-02T08:37:24Z\",\"showInAddressList\":null,\"sipProxyAddress\":null,\"state\":\"California\",\"streetAddress\":null,\"surname\":\"Test\",\"telephoneNumber\":\"666\",\"[email protected]\":\"directoryObjects/5f6851c3-99cc-4a89-936d-4bb44fa78a34/Microsoft.DirectoryServices.User/thumbnailPhoto\",\"usageLocation\":null,\"userPrincipalName\":\"[email protected]\",\"userType\":\"Member\"} 
--batchresponse_e42a30ca-0f3a-4c17-8672-22abc469cd16 
Content-Type: application/http 
Content-Transfer-Encoding: binary 

HTTP/1.1 200 OK 
DataServiceVersion: 3.0; 
Content-Type: application/json;odata=minimalmetadata;streaming=true;charset=utf-8 

{\"odata.metadata\":\"https://graph.windows.net/XXX.onmicrosoft.com/$metadata#directoryObjects/@Element\",\"odata.type\":\"Microsoft.DirectoryServices.User\",\"objectType\":\"User\",\"objectId\":\"dd35d761-e6ed-44e7-919f-f3b1e54eb7be\",\"deletionTimestamp\":null,\"accountEnabled\":true,\"signInNames\":[],\"assignedLicenses\":[],\"assignedPlans\":[],\"city\":null,\"companyName\":null,\"country\":null,\"creationType\":null,\"department\":null,\"dirSyncEnabled\":null,\"displayName\":\"Max Admin\",\"facsimileTelephoneNumber\":null,\"givenName\":null,\"immutableId\":null,\"isCompromised\":null,\"jobTitle\":null,\"lastDirSyncTime\":null,\"mail\":null,\"mailNickname\":\"maxadmin\",\"mobile\":null,\"onPremisesSecurityIdentifier\":null,\"otherMails\":[],\"passwordPolicies\":null,\"passwordProfile\":null,\"physicalDeliveryOfficeName\":null,\"postalCode\":null,\"preferredLanguage\":null,\"provisionedPlans\":[],\"provisioningErrors\":[],\"proxyAddresses\":[],\"refreshTokensValidFromDateTime\":\"2016-12-05T15:11:51Z\",\"showInAddressList\":null,\"sipProxyAddress\":null,\"state\":null,\"streetAddress\":null,\"surname\":null,\"telephoneNumber\":null,\"[email protected]\":\"directoryObjects/dd35d761-e6ed-44e7-919f-f3b1e54eb7be/Microsoft.DirectoryServices.User/thumbnailPhoto\",\"usageLocation\":null,\"userPrincipalName\":\"[email protected]\",\"userType\":\"Member\"} 
--batchresponse_e42a30ca-0f3a-4c17-8672-22abc469cd16-- 

Мне нужно, чтобы получить все это содержание как объекты (например, классические HttpResponseMessage, а не простые строки), чтобы получить код возврата HTTP, содержимое JSON и т. д. в качестве свойств и иметь возможность их обрабатывать.

Я знаю, как читать все эти раздельно содержание, но я не могу понять, как получить их как объекты, я только удалось получить содержимое строки:

var multipartContent = await response.Content.ReadAsMultipartAsync(); 
foreach (HttpContent currentContent in multipartContent.Contents) { 
    var testString = currentContent.ReadAsStringAsync(); 
    // How to get this content as an exploitable object? 
} 

В моем примере, СравниваемаяСтрока содержит:

HTTP/1.1 200 OK 
DataServiceVersion: 3.0; 
Content-Type: application/json;odata=minimalmetadata;streaming=true;charset=utf-8 

{\"odata.metadata\":\"https://graph.windows.net/XXX.onmicrosoft.com/$metadata#directoryObjects/@Element\",\"odata.type\":\"Microsoft.DirectoryServices.User\",\"objectType\":\"User\",\"objectId\":\"5f6851c3-99cc-4a89-936d-4bb44fa78a34\",\"deletionTimestamp\":null,\"accountEnabled\":true,\"signInNames\":[],\"assignedLicenses\":[],\"assignedPlans\":[],\"city\":null,\"companyName\":null,\"country\":null,\"creationType\":null,\"department\":\"NRF\",\"dirSyncEnabled\":null,\"displayName\":\"dummy1 Test\",\"facsimileTelephoneNumber\":null,\"givenName\":\"dummy1\",\"immutableId\":null,\"isCompromised\":null,\"jobTitle\":\"test\",\"lastDirSyncTime\":null,\"mail\":null,\"mailNickname\":\"dummy1test\",\"mobile\":null,\"onPremisesSecurityIdentifier\":null,\"otherMails\":[],\"passwordPolicies\":null,\"passwordProfile\":{\"password\":null,\"forceChangePasswordNextLogin\":true,\"enforceChangePasswordPolicy\":false},\"physicalDeliveryOfficeName\":null,\"postalCode\":null,\"preferredLanguage\":null,\"provisionedPlans\":[],\"provisioningErrors\":[],\"proxyAddresses\":[],\"refreshTokensValidFromDateTime\":\"2016-12-02T08:37:24Z\",\"showInAddressList\":null,\"sipProxyAddress\":null,\"state\":\"California\",\"streetAddress\":null,\"surname\":\"Test\",\"telephoneNumber\":\"666\",\"[email protected]\":\"directoryObjects/5f6851c3-99cc-4a89-936d-4bb44fa78a34/Microsoft.DirectoryServices.User/thumbnailPhoto\",\"usageLocation\":null,\"userPrincipalName\":\"[email protected]\",\"userType\":\"Member\"} 

Я просто не могу себе представить, чтобы разобрать эту строку вручную ... Так что если кто-то имеет ключ или может объяснить мне хороший способ, чтобы прочитать содержание, было бы неплохо.

Спасибо, Max

ответ

2

Вот как это можно сделать. Ключ для добавления нового типа контента «MsgType» заголовок в ответ:

var multipartContent = await response.Content.ReadAsMultipartAsync(); 
HttpResponseMessage workingResponse = null; 
foreach (HttpContent currentContent in multipartContent.Contents) { 
    // Two cases: 
    // 1. a "single" response 
    if (currentContent.Headers.ContentType.MediaType.Equals("application/http", StringComparison.OrdinalIgnoreCase) && !currentContent.Headers.ContentType.Parameters.Any(parameter => parameter.Name.Equals("msgtype", StringComparison.OrdinalIgnoreCase) && parameter.Value.Equals("response", StringComparison.OrdinalIgnoreCase))) { 
     currentContent.Headers.ContentType.Parameters.Add(new NameValueHeaderValue("msgtype", "response")); 
     workingResponse = await currentContent.ReadAsHttpResponseMessageAsync(); 
     // The workingResponse object contains a classic exploitable HttpResponseMessage (with IsSuccessStatusCode, Content.ReadAsStringAsync().Result, etc.) 
    } 
    // 2. a changeset response, which is an embedded multipart content 
    else { 
     var subMultipartContent = await currentContent.ReadAsMultipartAsync(); 
     foreach (HttpContent currentSubContent in subMultipartContent.Contents) { 
      currentSubContent.Headers.ContentType.Parameters.Add(new NameValueHeaderValue("msgtype", "response")); 
      workingResponse = await currentSubContent.ReadAsHttpResponseMessageAsync(); 
      // Same here, the workingResponse object contains a classic exploitable HttpResponseMessage 
     } 
    } 
} 

Thanks to darl0026