public unsafe static bool GetResponseHeader(
SafeWinHttpHandle requestHandle,
uint infoLevel,
ref char[] buffer,
ref uint index,
out string headerValue)
{
const int StackLimit = 128;
Debug.Assert(buffer == null || (buffer != null && buffer.Length > StackLimit));
int bufferLength;
uint originalIndex = index;
if (buffer == null)
{
bufferLength = StackLimit;
char* pBuffer = stackalloc char[bufferLength];
if (QueryHeaders(requestHandle, infoLevel, pBuffer, ref bufferLength, ref index))
{
headerValue = new string(pBuffer, 0, bufferLength);
return true;
}
}
else
{
bufferLength = buffer.Length;
fixed (char* pBuffer = buffer)
{
if (QueryHeaders(requestHandle, infoLevel, pBuffer, ref bufferLength, ref index))
{
headerValue = new string(pBuffer, 0, bufferLength);
return true;
}
}
}
int lastError = Marshal.GetLastWin32Error();
if (lastError == Interop.WinHttp.ERROR_WINHTTP_HEADER_NOT_FOUND)
{
headerValue = null;
return false;
}
if (lastError == Interop.WinHttp.ERROR_INSUFFICIENT_BUFFER)
{
// WinHttpQueryHeaders may advance the index even when it fails due to insufficient buffer,
// so we set the index back to its original value so we can retry retrieving the same
// index again with a larger buffer.
index = originalIndex;
buffer = new char[bufferLength];
return GetResponseHeader(requestHandle, infoLevel, ref buffer, ref index, out headerValue);
}
throw WinHttpException.CreateExceptionUsingError(lastError);
}