【发布时间】:2009-03-14 16:10:10
【问题描述】:
这里有个问题。
我有一个托管 silverlight 2 应用程序的 ASP.net 网站。 我希望该站点能够与 silverlight 应用程序来回通信,并且我正在通过 http 请求进行此操作。顺便说一句,如果有人知道更好的方法,请告诉我。
我的服务器设置了以下 http 侦听器。我从某处的教程网站复制了这个,因为它目前主要是实验:
HttpListener listener = new HttpListener ( );
listener.Prefixes.Add("http://localhost:4531/MyApp/");
listener.Start( );
// Wait for a client request:
HttpListenerContext context = listener.GetContext( );
// Respond to the request:
string msg = "You asked for: " + context.Request.RawUrl;
context.Response.ContentLength64 = Encoding.UTF8.GetByteCount (msg);
context.Response.StatusCode = (int) HttpStatusCode.OK;
using (Stream s = context.Response.OutputStream)
using (StreamWriter writer = new StreamWriter (s))
writer.Write (msg);
listener.Stop( );
我正在使用以下代码发送请求:
private void MyButton_Click(object sender, RoutedEventArgs e)
{
Button b = sender as Button;
b.Content = "Hello World";
Uri serviceUri = new Uri("http://localhost:4531/MyApp/");
WebClient downloader = new WebClient();
downloader.DownloadStringCompleted += new DownloadStringCompletedEventHandler(TestDownloadStoriesCompleted);
downloader.DownloadStringAsync(serviceUri);
}
void TestDownloadStoriesCompleted(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Error == null)
{
TextBox1.Text = e.Result;
}
}
我的问题是我可以使用几乎相同的代码从控制台应用程序连接到网络服务器(我通过在代码中设置断点对其进行了测试),但是当我单击 Silverlight 中的按钮时没有任何反应。 (我添加了“Hello World”来测试我确实将代理连接到按钮。)
我已经读到 silverlight 需要策略才能通过 webclient 进行连接,但如果我为服务器和 silverlight 应用程序使用相同的服务器和相同的域,则不应该是这种情况!
感谢您的所有回复!
编辑:我收到此异常:
System.Security.SecurityException ---> System.Security.SecurityException: 安全错误。
另外,基于我reading 显然是站点来源,xap 的部署 URI 和请求 URI 也必须属于同一端口。
但是,当我将服务器的属性设置为托管在特定端口上,并将侦听器设置为侦听同一端口时,它会失败并显示“进程无法访问该文件,因为它正在被使用”的消息通过另一个过程。我认为这是因为 http 侦听器无法侦听用于托管它的同一端口:| 但是,我怎样才能让 Silverlight 执行主机源网络客户端请求呢?
【问题讨论】:
标签: asp.net httpwebrequest silverlight-2.0 webclient