Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Xamarin HttpClient Stack detection in runtime

In Xamarin iOS application I'm able to specify which HttpClient implementation to use in runtime:

https://developer.xamarin.com/guides/cross-platform/macios/http-stack/

However this setting only affects HttpClients constructed using default ctor:

var client = new HttpClient()

But what if I want to add some request interception to my http client by supplying custom DelegatingHandler to the ctor? I will then use another ctor:

var myDel = new MyDel(RUNTIME_HANDLER_GOES_HERE);
var client = new HttpClient(myDel);

Ideally in runtime I need to know which httpHandler is selected in compile time project settings in order to myDel to wrap it in runtime. How do I do it?

UPD I was able to find the code responsible for selecting appropriate handler in mono's source: https://github.com/mono/mono/blob/master/mcs/class/System.Net.Http/HttpClientEx.cs#L28 however RuntimeOptions class is internal and I can only use it via reflection in runtime. In this case however Xamarin's linker strips RuntimeOptions from dll in release mode and the app crashes in release and adhoc builds but not in debug. Does anyone know what happens to RuntimeOptions in linker-enabled xamarin build so I'm able to utilise it to find out runtime httphandler?

like image 949
Anton Shabanov Avatar asked Jan 24 '26 18:01

Anton Shabanov


1 Answers

Don't fight the linker - it's removing it because it's a size optimization to be able to just use the required handler(s).

However you can still use reflection elsewhere, a place that the linker can't remove. You can see such an example in our HttpClient sample. Here's the important line:

typeof(HttpMessageInvoker).GetField("_handler", BindingFlags.Instance | BindingFlags.NonPublic)?.GetValue (client).GetType ();
like image 77
poupou Avatar answered Jan 26 '26 11:01

poupou



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!