【问题标题】:upload serialized data using WebClient使用 WebClient 上传序列化数据
【发布时间】:2023-03-31 22:06:01
【问题描述】:

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

如何使用 webclient 对类的对象进行 serailize 并发送到 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;

【问题讨论】:

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


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-04-10
      • 1970-01-01
      • 1970-01-01
      • 2020-02-14
      • 1970-01-01
      • 2019-03-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多