c# - 对 Web Api 的 MVC 请求

标签 c# asp.net-mvc asp.net-web-api

我正在尝试构建一个通过 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/

相关文章:

c# - 将 URI 映射到 LINQ-to-SQL 中的字符串字段

c# - 覆盖接口(interface)中声明的方法实现

c# - 依赖倒置原则和放置接口(interface)的位置

jquery - 使用 MVC 4 和 Ajax 上传文件

c# - 将 WebSocket 与 ASP.NET Web API 结合使用

asp.net-web-api - Hot Towel/Durandal/Breeze.js : how to vertically secure data calls?

javascript - 数据集返回 JavaScript AngularJS

c# - 如何在 screwturn wiki 中测试运行插件

c# - 为什么在使用 pex 迭代 PropertyInfo 时出现 indexoutofboundsexception?

asp.net-mvc - MVCSiteMapProvider 面包屑不正确的父节点 ID