如何从asp.net使用webApi?

时间:2014-10-26 09:11:44

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

我需要做一个从数据库调用api的项目

并创建另一个项目并调用仅在其控制器中包含api的旧项目

我面对这些问题 1-我想从api返回一个对象,它接受对象和返回对象 如

这是我的api,它位于“testController”

  [HttpPost]
            [ActionName("fetch_information")]
            public login_info fetch_information(login_info_request request)

我想从另一个项目中调用这个api 如

      public login_info fetch_information(login_info_request request)
            {

                HttpClient client = new HttpClient();
                client.BaseAddress = new Uri("http://localhost:58295/fetch_information");


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


                HttpResponseMessage response = client.GetAsync("api/"+request+"").Result;
                if (response.IsSuccessStatusCode)
                {              
                    return null;
  here I want to return an object of "login_info " 
                }
                else
                {
                    return null;
                }
            }

我的问题是 我在哪里可以给它请求对象数据“login_info_request”? 我在哪里可以从api“login_info”接收对象?

提前致谢

1 个答案:

答案 0 :(得分:1)

您的代码的问题在于您发出了GET请求,而您显示的Web API方法需要POST。

所以:

HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:58295/fetch_information");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

login_info_request req = ... 
string postBody = JsonConvert.SerializeObject(req);
HttpContent content = new StringContent(postBody, Encoding.UTF8, "application/json");
HttpResponseMessage response = client.PostAsync("api/" + request, content).Result;
if (response.IsSuccessStatusCode)
{
    // Read the response body as string
    string json = response.Content.ReadAsStringAsync().Result;

    // deserialize the JSON response returned from the Web API back to a login_info object
    return JsonConvert.DeserializeObject<login_info>(json);
}
else
{
    return null;
}

如果您使用Microsoft ASP.NET Web API 2.2 Client Libraries NuGet,则可以使用extension method来缩短代码:

if (response.IsSuccessStatusCode)
{
    return response.Content.ReadAsAsync<login_info>().Result;
}
else
{
    return null;
}