How to consume a webApi from asp.net? [duplicate]

谁都会走 提交于 2020-01-17 17:29:10

问题


I need to do project which call api's from database

and make another project and call the old one which contain api's only in its controller

I face those problems 1- I want to return an object from api which takes object and return object as

this is my api which locate in "testController"

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

and I want to call this api from another project as

      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;
                }
            }

my question is where can I give it request object data "login_info_request "? and where can I recieve object from api "login_info"?

thanks in advance


回答1:


The problem with your code is that you made a GET request whereas the Web API method you have shown expects POST.

So:

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;
}

And if you use the Microsoft ASP.NET Web API 2.2 Client Libraries NuGet there is an extension method which will allow you to shorten the code:

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


来源:https://stackoverflow.com/questions/26571451/how-to-consume-a-webapi-from-asp-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!