I'm using xunit to write some unit tests that will be testing a subclass of HttpClient
that I've written that also uses a DelegateHandler
. I'm trying to use a HttpMessageHandler
to mock the responses that I'd be getting from calling the Get/Post calls on the HttpClient
. I'm passing the message handler to my delete handler's constructor through a HttpClientHandler.CreatePipeline()
call. However, when I run the unit test, I get this exception:
System.TypeAccessException : Attempt by security transparent method 'System.Net.Http.HttpClientFactory.CreatePipeline(System.Net.Http.HttpMessageHandler, System.Collections.Generic.IEnumerable`1<System.Net.Http.DelegatingHandler>)' to access security critical type 'System.Net.Http.HttpMessageHandler' failed.
Stack Trace:
at System.Net.Http.HttpClientFactory.CreatePipeline(HttpMessageHandler innerHandler, IEnumerable`1 handlers)
My constructor looks like this:
public MyHttpClient(HttpMessageHandler handler) :
base(HttpClientFactory.CreatePipeline(
new HttpClientHandler(),
new[]
{
new MyDelegateHandler(handler)
}))
{ }
Constructor for my delegate handler:
public MyDelegateHandler(HttpMessageHandler messageHandler) :
base(messageHandler)
{ }
And some code from my unit test:
var handler = new MyMessageHandler("response content");
MyHttpClient client = new MyHttpClient(handler);
var task = client.GetAsync("https://example.com");
(note that the exception occurs before I get to call GetAsync()
)
I've tried adding security attributes to all my calls, including the method that runs the unit test (from this question: Attempt by security transparent method X to access security critical method Y failed)
I've also tested by removing the delegate handler completely and passing the message handler directly into the MyHttpClient
constructor and that works fine.
I've also tried adding any number/combination of the following attributes to the AssemblyInfo.cs
files:
[assembly: SecurityRules(SecurityRuleSet.Level1)]
[assembly: AllowPartiallyTrustedCallers]
[assembly: SecurityTransparent()]
Is there anything else I can do to get around the access exception? I'd like to be able to test the delegate handler.
UPDATE: It appears I am getting this exception whether I am passing in a message handler or not. Simply calling the CreatePipeline()
method throws this exception.