我正在尝试构建一个通过PCL向WebApi请求的MVC。我正在发送一个get请求,被困在等待回复的人身上。邮递员返回正确的值。我在发送时也没有异常。这三个项目都在同一个解决方案上。
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( );
Web
public class ValuesController : ApiController
{
// GET api/values
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
}
此外,在呈现控制器视图之前,如何在MVC中等待响应?
发布于 2015-10-17 17:43:48
好的,我找到了最好的解决办法。阻塞线程不是一个好主意。
这就是解决办法
PCL
public async Task<HttpResponseMessage> Register()
{
HttpRequestMessage request = new HttpRequestMessage
{
RequestUri = new Uri( _http.BaseAddress, "account/register/" ),
Method = HttpMethod.Post,
Content = new StringContent( "{\"Email\": \"email@yahoo.com\",\"Password\": \"Password!1\",\"ConfirmPassword\": \"Password!1\"}",
Encoding.UTF8,
_contentType
),
};
HttpResponseMessage response = new HttpResponseMessage();
try
{
response = await _http.SendAsync( request, CancellationToken.None );
}
catch (Exception e)
{
Debugger.Break();
}
return response;
}
MVC客户端
public async Task<ViewResult> Index( )
{
var thisTask = await Api.Register( );
return View();
}
发布于 2015-10-14 17:03:35
在类库中,创建方法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();
解决了你们的两个问题。
https://stackoverflow.com/questions/33107177
复制相似问题