如何在Silverlight应用程序中设置WebClient类中的post参数

时间:2010-03-31 18:49:45

标签: silverlight webclient

首先,我编写了一个简单的php页面,它从POST参数中获取一些变量,例如查询和认证字符串,并将结果作为xml返回。我打算使用Silverlight应用程序中的WebClient类调用此页面。我正在使用POST,因为我们使用任何有效的sql语句查询数据库,而不仅仅是select语句。 WebClient类使用UploadDataAsync方法发布到http服务器,但是它需要将post参数作为NameValueCollection传递。 Silverlight运行时中缺少此类。我该怎么办?

2 个答案:

答案 0 :(得分:1)

使用WebRequest API而不是WebClient API。

var request = WebRequest.Create(requestUriString);

request.Method = "POST";

request.BeginGetRequestStream()

答案 1 :(得分:1)

        WebClient webClient = new WebClient();
        webClient.Headers["content-type"] = "application/x-www-form-urlencoded";
        webClient.Encoding = Encoding.UTF8;
        webClient.UploadStringCompleted += new UploadStringCompletedEventHandler(webClient_UploadStringCompleted);
        webClient.UploadStringAsync(new Uri(courseListUrl, UriKind.Absolute), "POST", apend);

apend是你的字符串,你通过POST-Method发送

在UploadCompleteMethod:

之后
 void webClient_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
 {
      string k = e.Result;
 }

如果你想在WebClient中使用Cookies,你也可以这样做,但你必须从WebClient创建一个Descendant类,如下所示:

 public class CookieAwareWebClient : WebClient
 {
    private CookieContainer m_container = new CookieContainer();

    [System.Security.SecuritySafeCritical]
    public CookieAwareWebClient() : base() { }


    protected override WebRequest GetWebRequest(Uri address)
    {
        WebRequest request = base.GetWebRequest(address);
        if (request is HttpWebRequest)
        {
            (request as HttpWebRequest).CookieContainer = m_container;
        }
        return request;
    }
}

之后,您只需将WebClient webClient = new WebClient();更改为CookieAwareWebClient webClient = new CookieAwareWebClient();

即可