Search code examples
xamarinportable-class-library

HttpWebRequiest.AllowAutoRedirect not found in PCL


I'm new to Xamarin, so I hope this is not a silly question :)

I am developing a PCL that will function as SDK (NuGet package) for customers to use for their Http APIs. There's a lot of logic that should be done on both iOS and Android, so I figured PCL is the way to go. The API I'm wrapping is the HttpWebRequest, basically I expose the exact same API and meddle with the requests before they're being sent.

One of the things I need to do is to ensure all redirections go through me, in order to have cookies control.

I found that the proper way to do it is to set: HttpWebRequest.AllowAutoRedirect = false

However when I try to to this, I get an error: 'HttpWebRequest' does not contain a definition for 'AllowAutoRedirect'...

This is a sample code:

using System;
using System.IO;
using System.Net;
using System.Threading.Tasks;

namespace PCLTest.Net
{
    public class MyHttpWebRequest
    {
        HttpWebRequest request;

        public bool AllowAutoRedirect
        {
            get
            {
                return request.AllowAutoRedirect;
            }
            set
            {
                request.AllowAutoRedirect = value;
            }
        }
    }
}

What am I missing?


Solution

  • OK, so I didn't find out why this API is hidden and how to make the framework expose it, but I did end up solving this by reflection like this:

    using System;
    using System.IO;
    using System.Net;
    using System.Threading.Tasks;
    
    namespace PCLTest.Net
    {
        public class MyHttpWebRequest
        {    
            HttpWebRequest request;
    
            public bool AllowAutoRedirect
            {
                get
                {
                    Type t = request.GetType();
                    PropertyInfo pi = t.GetRuntimeProperty("AllowAutoRedirect");
                    return (bool)pi.GetValue(request);
                }
                set
                {
                    request.AllowAutoRedirect = value;
                }
            }
        }
    }