首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >MVC对Web的请求

MVC对Web的请求
EN

Stack Overflow用户
提问于 2015-10-13 15:50:55
回答 2查看 1.8K关注 0票数 1

我正在尝试构建一个通过PCL向WebApi请求的MVC。我正在发送一个get请求,被困在等待回复的人身上。邮递员返回正确的值。我在发送时也没有异常。这三个项目都在同一个解决方案上。

PCL

代码语言:javascript
运行
复制
        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

代码语言:javascript
运行
复制
       var result = apiClient.GetIndex( );

Web

代码语言:javascript
运行
复制
public class ValuesController : ApiController
{
    // GET api/values
    public IEnumerable<string> Get()
    {
        return new string[] { "value1", "value2" };
    }
}

此外,在呈现控制器视图之前,如何在MVC中等待响应?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2015-10-17 17:43:48

好的,我找到了最好的解决办法。阻塞线程不是一个好主意。

这就是解决办法

PCL

代码语言:javascript
运行
复制
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客户端

代码语言:javascript
运行
复制
    public async Task<ViewResult> Index( )
    {
        var thisTask = await Api.Register( );

        return View();
    }
票数 0
EN

Stack Overflow用户

发布于 2015-10-14 17:03:35

类库中,创建方法GetIndex,如下所示,

代码语言:javascript
运行
复制
    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调用方法中,

代码语言:javascript
运行
复制
var result = apiClient.GetIndexAsync().Wait();

解决了你们的两个问题。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/33107177

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档