使用多个字符串参数调用Post Web API?

时间:2013-12-08 13:26:27

标签: c# asp.net-mvc web-services asp.net-web-api

我们如何调用以下网络API?

[HttpPost]
public bool ValidateAdmin(string username, string password)
{
    return _userBusinessObject.ValidateAdmin(username, password);
}

我已经编写了以下代码,但它不起作用404 (Not Found)

string url = string.Format("api/User/ValidateAdmin?password={0}", password);
HttpResponseMessage response = Client.PostAsJsonAsync(url, username).Result;
response.EnsureSuccessStatusCode();
return response.Content.ReadAsAsync<bool>().Result;

修改
我对Url很肯定,但它说404 (Not Found)

1 个答案:

答案 0 :(得分:2)

我在类似的情况下也喜欢这个:

MediaTypeFormatter jsonFormatter = new JsonMediaTypeFormatter();
HttpContent datas = new ObjectContent<dynamic>(new { 
    username= username, 
    password= password}, jsonFormatter);

var client = new HttpClient();

client.DefaultRequestHeaders.Accept.Add(
    new MediaTypeWithQualityHeaderValue("application/json"));

var response = client.PostAsync("api/User/ValidateAdmin", datas).Result;

if (response != null)
{
    try
    {
        response.EnsureSuccessStatusCode();
        return response.Content.ReadAsAsync<bool>().Result;

        ...