问题
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