【问题标题】:Consume locally hosted REST from Silverlight?从 Silverlight 使用本地托管的 REST?
【发布时间】:2010-10-09 07:21:32
【问题描述】:

我正在构建 Silverlight / Windows Azure 应用程序。

我正在尝试从 Web 角色公开的 REST API 中读取一些简单数据。

    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");

    }

不幸的是,它总是失败并显示以下消息:

NotSupportedException:“URI 前缀 无法识别。”

我在这里做错了什么?是在抱怨“本地主机”吗?有没有更简单的方法来访问我自己的解决方案中公开的服务? (这可能是“添加服务引用”的用途吗?)

更新http:// 添加到 URI 使其正常工作。 (但显然,一旦它部署到 Azure,这将不起作用?)

仅使用相对路径,如 /expenseservice.svc/expenses 会失败,并出现以下异常:

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)

【问题讨论】:

    标签: c# visual-studio silverlight rest


    【解决方案1】:

    你指定给 Uri 构造函数的 uri 字符串是无效的,它应该是这样的

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

    但我很确定它在 Azure 结构上也不起作用:你不能在上面硬编码端口信息,因为它们可以改变。嗯,此外,我确信它不会在结构上工作,因为 SL 应用程序在客户端上运行,而且......客户端上的 localhost 是客户端,而不是服务器

    您应该使用相对或绝对 uri 而不指定主机。

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

    应该可以解决问题。

    【讨论】:

    • 相对 URI 不起作用。它会导致异常(见上文)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-12-03
    • 1970-01-01
    • 1970-01-01
    • 2010-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多