Skip to content

Instantly share code, notes, and snippets.

@smaglio81
Created October 15, 2019 05:35
Show Gist options
  • Save smaglio81/acd2942c1472c453fbe0b8519b9edd98 to your computer and use it in GitHub Desktop.
Save smaglio81/acd2942c1472c453fbe0b8519b9edd98 to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Reflection;
using System.Text;
namespace YourNamespace
{
public static class HttpMessageInvokerExtensions
{
/// <summary>
/// This helps implement <see cref="DelegatingHandler" />.
/// DelegatingHandler: https://msdn.microsoft.com/en-us/library/system.net.http.delegatinghandler(v=vs.118).aspx
/// -> extends HttpMessageHandler: https://msdn.microsoft.com/en-us/library/system.net.http.httpmessagehandler(v=vs.118).aspx
/// HttpMessageInvoker: https://msdn.microsoft.com/en-us/library/system.net.http.httpmessageinvoker(v=vs.118).aspx
/// -> Has constructor that takes HttpMessageHandler
/// </summary>
private const string InternalHandlerFieldName = "_handler";
private const string InternalHandlerFieldNameAlt = "handler";
private const BindingFlags InternalHandlerBindingFlags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance;
public static void AppendDelegatingHandler(this HttpMessageInvoker client, DelegatingHandler handler)
{
throw new NotImplementedException();
}
internal static FieldInfo GetInternalSendAsyncHandlerFieldInfo(this HttpMessageInvoker client)
{
FieldInfo internalField = null;
var currentType = client.GetType();
while (currentType != null)
{
if (currentType == typeof(HttpMessageInvoker))
{
internalField = currentType.GetField(InternalHandlerFieldName, InternalHandlerBindingFlags);
if (internalField == null)
{
internalField = currentType.GetField(InternalHandlerFieldNameAlt, InternalHandlerBindingFlags);
}
break;
}
currentType = currentType.BaseType;
}
if (internalField == null)
{
throw new Exception("Could not find internal HttpMessageHandler field.");
}
return internalField;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment