从外部web api如何反应How to get response from external web api

- 此内容更新于:2015-01-06
主题:

原文:

I have a webapi controller which calls a method of a class. The method in that class should call an external api, get the response as object and return to the webapi controller. I am facing some problem getting the response from external api in the c# class file.

Origin Webapi

[HttpPost]
public HttpResponseMessage RequestVend(CustomObject obj)
{
    var aa = DependencyManager.Resolve<IAA>();
    var response = aa.GetResponse(obj));
    return Request.CreateResponse(HttpStatusCode.OK, response);
}

AA.cs

public async Task<ResponseObj> GetResponse(CustomObject obj)
{
    var response = await GetExternalResponse(obj);
    return response;
}

private async Task<ResponseObj> GetExternalResponse(CustomObject obj)
{
    var client = new HttpClient();
    HttpResponseMessage response = await client.PostAsJsonAsync(_address, obj);
    response.EnsureSuccessStatusCode();
    if (response.IsSuccessStatusCode)
    {
        string responseString = await response.Content.ReadAsStringAsync();
        Console.WriteLine(responseString);
        Console.WriteLine("HTTP Status: {0}, Reason {1}. Press ENTER to exit", response.StatusCode, response.ReasonPhrase);
    }
    else
    {
        Console.WriteLine("Failed to call the API. HTTP Status: {0}, Reason {1}", response.StatusCode, response.ReasonPhrase);
    }
    var result = await response.Content.ReadAsAsync<VendResponse>();
    return result;
}

Can anyone please help how to achieve this.

Balanikas的回复:这个问题是什么?

(原文:what is the problem?)

tom的回复:帖子异常堆栈跟踪如果你面对它!

(原文:Post the exception stack-trace if you are facing it!)

JK.的回复:一个问题通常有一个问号在它所以人们知道这个问题是什么。

(原文:A question usually has a question mark somewhere in it so people know what that question is.)