使用WebClient上传序列化数据

时间:2011-01-10 20:19:27

标签: asp.net-mvc model-view-controller webclient webclient.uploaddata

简单要求。我有一个类 - 用户 - {userId,userName,age}。

如何使用webclient搜索类的对象并发送到url(使用post)。

下面的东西。

将用户对象序列化为postdata格式的最佳方法是什么。

WebClient client = new WebClient();
        client.Encoding = System.Text.Encoding.UTF8;
        client.Credentials = CredentialCache.DefaultNetworkCredentials;
        string postData = "orderId=5&status=processed2&advertId=ADV0001a";
        byte[] postArray = Encoding.ASCII.GetBytes(postData);
        client.Headers.Add("Content-Type","application/x-www-form-urlencoded");
        byte[] responseArray = client.UploadData(address, postArray);
        var result = Encoding.ASCII.GetString(responseArray);
        return result;

1 个答案:

答案 0 :(得分:0)

我会将以下简化应用于您的代码:

using (var client = new WebClient())
{
    client.Credentials = CredentialCache.DefaultNetworkCredentials;
    var data = new NameValueCollection 
    {
        { "userId", user.Id },
        { "userName", user.Name },
        { "age", user.Age }
    };
    var responseArray = client.UploadValues(address, data);
    return Encoding.ASCII.GetString(responseArray);
}