简体   繁体   中英

Consume locally hosted REST from Silverlight?

I'm building a Silverlight / Windows Azure app.

I'm trying to read some simple data from a REST API exposed from the web role.

    private void MainPage_Loaded(object sender, RoutedEventArgs args)
    {
        // ...

        WebClient data = new WebClient();
        data.DownloadStringCompleted += new DownloadStringCompletedEventHandler(data_DownloadStringCompleted);
        data.DownloadStringAsync(new Uri("localhost:88/expenseservice.svc/expenses"));
    }

    void data_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
    {
        if (e.Error != null) 
        {
            MessageBox.Show(e.Error.Message);
            return;
        }

        XElement xmlStrs = XElement.Parse(e.Result);

        strBox.ItemsSource = xmlStrs.Descendants("ArrayOfstring");

    }

Unfortunately, it always fails with the following message:

NotSupportedException: "The URI prefix is not recognized."

What am I doing wrong here? Is it complaining about "localhost"? Is there an easier way to get access to services exposed within my own solution? (Is this possibly what "Add Service Reference" is for?)

Update Adding http:// to the URI makes it work fine. (But apparently this won't work once it's deployed to Azure?)

Just using a relative path, like /expenseservice.svc/expenses fails with the following exception:

System.UriFormatException: Invalid URI: The format of the URI could not be determined.
   at System.Uri.CreateThis(String uri, Boolean dontEscape, UriKind uriKind)
   at System.Uri..ctor(String uriString)
   at ExpenseCalc_SilverLight.MainPage.MainPage_Loaded(Object sender, RoutedEventArgs args)
   at MS.Internal.CoreInvokeHandler.InvokeEventHandler(Int32 typeIndex, Delegate handlerDelegate, Object sender, Object args)
   at MS.Internal.JoltHelper.FireEvent(IntPtr unmanagedObj, IntPtr unmanagedObjArgs, Int32 argsTypeIndex, Int32 actualArgsTypeIndex, String eventName)

the uri string you specified to the Uri constructor is invalid, it should look like

new Uri("http://localhost:88/expenseservice.svc/expenses")

But I am quite sure it won't work neither on the Azure fabric: you can't hard code port informations on it, as they can change. Hmm Furthermore, I am sure it won't work on the fabric, as the SL app runs on the client and well.. localhost on the client IS the client, not the server

you should use relative or absolute uri without specifying the host.

new Uri("/expenseservice.svc/expenses",UriKind.Relative)

should do the trick.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM