如何在body请求中向web API发送参数?

时间:2016-10-25 11:08:45

标签: .net asp.net-web-api request

我正在尝试从控制台应用程序中使用WebAPI,作为集成测试的一部分。我用这个方法:

private static string Consume(string endpoint, string user, string password)
{
    var client = new HttpClient();
    client.BaseAddress = new Uri(endpoint);
    client.DefaultRequestHeaders.Accept.Clear();
    client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

    string body = "{\"User\":\"" + user + "\",\"Password\":\"" + password + "\"}";   
    var response = client.PostAsync("api/ticket", new StringContent(body, Encoding.UTF8, "application/json")).Result;
    response.EnsureSuccessStatusCode();
    if (response.IsSuccessStatusCode)
            ... //process

    return string.Empty;
}

我对将参数发送到WebAPI方法的方式感到非常满意,我更喜欢使用类似的对象:

public class Credentials
{
    public string User { get; set; }
    public string Password { get; set; }
}

并将其放入体内。有没有人对此提出建议?

2 个答案:

答案 0 :(得分:3)

使用Newtonsoft.Json库序列化您的凭证对象。 您的Consume功能就像这样

private static string Consume(string endpoint, string user, string password)
{
    var client = new HttpClient();
    client.BaseAddress = new Uri(endpoint);
    client.DefaultRequestHeaders.Accept.Clear();
    client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

    var credential = new Credentials { User = user, Password = password };
    var credentialString = Newtonsoft.Json.JsonConvert.SerializeObject(credential, Formatting.None);


    var response = client.PostAsync("api/ticket", credentialString).Result;
    response.EnsureSuccessStatusCode();
    if (response.IsSuccessStatusCode)
            ... //process

    return string.Empty;
}

credentialString是序列化Credentials类对象的字符串。

答案 1 :(得分:3)

您可以像这样使用发送对象。

var _content = new StringContent(JsonConvert.SerializeObject(yourobject), Encoding.UTF8, "application/json");
var result = _client.PostAsync(yourapi, _content).Result;