通过Web客户端post方法C#传递两个JSON对象

时间:2015-03-05 09:23:16

标签: c# post webclient asp.net-web-api

我需要在C#中使用Web客户端方法将下面的对象作为post方法的参数传递。

     {
    "company":
    {
        "id": "e63dfcab345260b2591f585126ede56627db4ef2"
    },
    "requestor":
    {
        "id": "",
        "email": "customer@example.com ",
        "firstName": "Test",
        "lastName": "Requestor",
        "role": "employerAdmin",
        "phone": "(415)1112222",
        "title": "HR Manager"
    }
}

我像这样转换

company[id]=e63dfcab345260b2591f585126ede56627db4ef2&requestor[id]=&requestor[email]=customer@example.com+&requestor[firstName]=Test&requestor[lastName]=Requestor&requestor[role]=employerAdmin&requestor[phone]=(415)1112222&requestor[title]=HR+Manager

但是我得到了无效的参数错误。请帮我。提前谢谢。

我的整个代码如下:

 using (var Requestor = new System.Net.WebClient())
            {

                string url = "https://stormaas-pre.inflection.com:8443/v1/Requestor?";
                string parameters = "company[id]='757563a3-67df-4a6e-9ef9-d89d57d41e0d'&requestor[id]=''&requestor[email]='customer@example.com'&requestor[firstName]='Test'&requestor[lastName]='Requestor'&requestor[role]='employerAdmin'&requestor[phone]='(415)1112222'&requestor[title]='HRManager'";
                Requestor.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");
                Requestor.Credentials = new System.Net.NetworkCredential("xyz:xyz!", "");
                Requestor.Encoding = System.Text.Encoding.UTF8;
                Requestor.Headers[HttpRequestHeader.ContentType] = "application/json";
                Requestor.Headers[HttpRequestHeader.Accept] = "text/xml";
                string res = Requestor.UploadString(url, "POST", parameters);
            }

2 个答案:

答案 0 :(得分:5)

您可以为Requestor,Company创建POCO类,如下所示,并使用JSON.net为您进行转换。

public class Company
{
    public string Id { get; set; }
    // Other properties
}

public class Requestor
{
    public string Id { get; set; }

    public string Email { get; set; }

    public string FirstName { get; set; }

    public string LastName { get; set; }
    // Other properties
}

public class Container
{
    public Company Company { get; set; }

    public Requestor Requestor { get; set; }
}

var requestor = new Container();
requestor.Company = new Company { Id = "sampleid" };
requestor.Requestor = new Requestor
{
    FirstName = "test",
    LastName = "testname"
};

JsonSerializerSettings settings = new JsonSerializerSettings();
settings.ContractResolver = new CamelCasePropertyNamesContractResolver();
var data = JsonConvert.SerializeObject(requestor, settings);

WebClient client = new WebClient();
client.Headers.Add(HttpRequestHeader.ContentType, "application/json");
// Code for the credentials etc
client.UploadString(@"your url", data);

希望这会有所帮助。为此,您需要引用JSON.net。由于您将.net 4.5与Web API一起使用,因此您应该已经有了参考。

答案 1 :(得分:0)

您收到无效参数错误,因为网址中不允许使用方括号。如果您想使用RFC 1738中未包含的字符,则必须使用HttpUtility.UrlEncode("String")(msdn reference