如何使用List <object>作为参数来使用WCF POST

时间:2017-03-24 06:27:07

标签: c# asp.net web-services wcf http-post

我有这样的课程定义:

public class Newuser
    {
        [DataMember]
        public string username { get; set; }

        [DataMember]
        public List<UserDetail> u_details{ get; set; } 

    }


public class UserDetail
    {
        [DataMember]
        public string age { get; set; }

        [DataMember]
        public string gender { get; set; } 

    }

并声明[OperationContract]喜欢:

[OperationContract]
        [WebInvoke(Method = "POST",
         ResponseFormat = WebMessageFormat.Json,
         RequestFormat = WebMessageFormat.Json,
         UriTemplate = "/addUser"
         )]
        void addUser(Newuser usr);

通常,我使用以下代码来使用WCF POST:

 BudgetTransactionRequest cb = new BudgetTransactionRequest
                {
                    category = "category",
                    amount = 2000.000
                };

                WebClient proxy = new WebClient();
                proxy.Headers["Content-Type"] = "application/json";
                MemoryStream ms = new MemoryStream();
                DataContractJsonSerializer serialize = new DataContractJsonSerializer(typeof(CreateBudget));
                serialize.WriteObject(ms, cb);
                byte[] data = proxy.UploadData("http://localhost:1910/Service1.svc/adduser", "POST", ms.ToArray());
                Stream stream = new MemoryStream(data);
                DataContractJsonSerializer obj = new DataContractJsonSerializer(typeof(CreateBudget));

但是,当对象包含列表时,我很难找到使用此服务的正确方法。如何通过列表传递多个对象参数?

1 个答案:

答案 0 :(得分:0)

您可以在WCF端使用查询参数来获取值。

var username = WebOperationContext.Current.IncomingRequest.UriTemplateMatch.QueryParameters["username"];

var password = WebOperationContext.Current.IncomingRequest.UriTemplateMatch.QueryParameters [“password”];

 **This you can use  to consume WCF POST:**

      HttpWebRequest req = null;
        HttpWebResponse resp = null;
       string baseAddress = "http://localhost:1910/Service1.svc";
        try
        {
            req = (HttpWebRequest)WebRequest.Create(baseAddress + "/adduser?Username=" + username+ "&Password=" + password);
            req.Method = "POST";
            req.ContentType = "text/xml; encoding = UTF-8";
            using (StreamWriter writer = new StreamWriter(req.GetRequestStream()))
            {
                writer.WriteLine(your_json_data);
            }
            resp = req.GetResponse() as HttpWebResponse;               
        }