Search code examples
silverlightrestproxyhttpwebrequestsilverlight-5.0

How to call an external REST API in Silverlight


Assuming I don't control the server and can't put a crossdomain.xml or clientaccesspolicy.xml file there, how can I make http calls inside a Silverlight app to an external REST API, without having to use javascript to do it and then pass the data to the Silverlight app?


Solution

  • I ended up implementing an ASP.NET proxy similar to what's described here

    and then adding the following code to the Silverlight App:

        public class Handler : IWebRequestCreate
        {
            public WebRequest Create(Uri uri)
            {
                return WebRequestCreator.ClientHttp.Create(new Uri("http://localhost:3234/Proxy.ashx?" + Uri.EscapeUriString(uri.OriginalString)));
            }
        }
    
        public MainPage()
        {
            InitializeComponent();
    
            HttpWebRequest.RegisterPrefix("http://", new Handler());
            HttpWebRequest.RegisterPrefix("https://", new Handler());
    
            (...rest of code...)
        }
    

    One caveat is that on the rest of the code one must be carefull to always use HttpWebRequest.Create and never HttpWebRequest.CreateHttp