Skip to main content
 首页 » 编程设计

c#之对 Web Api 的 MVC 请求

2024年05月29日41dflying

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

这解决了你的两个问题。