我正在尝试构建一个通过 PCL 请求 WebApi 的 MVC。我正在发送一个获取请求并卡在等待响应中。 postman 返回正确的值。我也没有在发送时收到异常。这 3 个项目都在同一个解决方案上。
PCL
HttpResponseMessage httpResponse = null;
try
{
httpResponse = await _http.GetAsync( "http://localhost:43818/api/values" );
}
catch (Exception e)
{
var meessage = e.Message;
var stack = e.StackTrace;
}
if (httpResponse.StatusCode == HttpStatusCode.OK)
{
string json = await httpResponse.Content.ReadAsStringAsync( );
}
所以问题在于,在 PCL 中,它没有通过等待,而是卡住了。
MVC
var result = apiClient.GetIndex( );
网络 API
public class ValuesController : ApiController
{
// GET api/values
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
}
此外,在呈现 Controller View 之前,我如何在 MVC 中等待响应
最佳答案
在您的类库 (PCL) 中,如下创建方法 GetIndex,
public async Task GetIndexAsync()
{
HttpResponseMessage httpResponse = null;
try
{
_http.BaseAddress = new Uri("http://localhost:43818/");
httpResponse = await _http.GetAsync("api/values");
}
catch (Exception e)
{
var meessage = e.Message;
var stack = e.StackTrace;
}
if (httpResponse.StatusCode == HttpStatusCode.OK)
{
string json = await httpResponse.Content.ReadAsStringAsync();
}
}
在MVC调用方法如下,
var result = apiClient.GetIndexAsync().Wait();
这解决了你的两个问题。
关于c# - 对 Web Api 的 MVC 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33107177/