Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/react-native/7.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何完成此REST实现?_C#_.net - Fatal编程技术网

C# 如何完成此REST实现?

C# 如何完成此REST实现?,c#,.net,C#,.net,MyService使用HttpClient.GetAsync()调用RESTURI。我从同一解决方案中控制台应用程序的主方法调用service方法,但返回以下结果: Id = 3, Status = WaitingForActivation, Method = "{null}", Result = "{Not yet computed}" 我需要做什么来完成这个REST实现 我的服务: using System.Net.Http; using System.Threading.Tasks;

MyService使用HttpClient.GetAsync()调用RESTURI。我从同一解决方案中控制台应用程序的主方法调用service方法,但返回以下结果:

Id = 3, Status = WaitingForActivation, Method = "{null}", Result = "{Not yet computed}"
我需要做什么来完成这个REST实现

我的服务:

using System.Net.Http;
using System.Threading.Tasks;

namespace Services
{
    public class MyService
    {
        private static HttpClient Client = new HttpClient();
        public void GetData()
        {
            var result = await Client.GetAsync("https://www.test.com/users");
        }
    }
}
来自控制台Main()的服务调用:

更新

好的,我更新了我的方法实现,如下所示:

    public async Task<HttpResponseMessage> GetData()
    {
        var result = await Client.GetAsync("https://www.test.com/users");
        return result;
    }
公共异步任务GetData() { var result=await Client.GetAsync(“https://www.test.com/users"); 返回结果; }
但是,这仍然返回与我在原始帖子中包含的值相同的值。我在这里遗漏了什么?

您没有从方法返回任何内容

public async Task GetData()
        {
            return await Client.GetAsync("https://www.test.com/users");
        }

从方法返回结果。

重构GetData以返回异步任务。@mason OP使用HttpClient有何错误?您应该使用私有静态实例。为什么要为简单的GET请求引入单独的库/依赖项?如果要在方法中使用WAIT,则必须将方法标记为async。如果您的方法被标记为async,那么它几乎应该总是返回一个任务或一个任务。顺便说一下,我不建议直接使用HttpClient。相反,看看Flurl或RestSharp。@maccettura他们不一定是做错了,我误解了。我读得太快了,认为他们每次都在实例化一个实例,而不是静态的。但是,每个域应该有一个HttpClient。因此,如果有另一个服务访问同一个域,或者该服务访问其他域,这可能是一个问题。HttpClient使事情变得比必须的困难得多。切换到Flurl或RestSharp可以防止您陷入这些陷阱,具有更好的语法,而且还可以为您进行JSON转换。@maccettura HttpClient存在问题的另一个例子是它不响应DNS更改。假设您的服务中有一个静态HttpClient,然后它调用的服务器更改了IP地址(可能是第三方,或者您的it部门正在更改DNS记录以指向不同的内部服务器)。现在,您的服务将停止工作,因为它尚未接收到新地址。修复它的唯一方法是重新启动服务。这很麻烦,你可能根本不知道服务失败的原因是什么。你不能只返回结果。那还是不会编译的,绝对不会。您还需要更改返回类型。它仍然无法编译。你以前用过
wait
吗?我更新了答案。请看一看。希望它能帮上忙。不,仍然无法编译。如果要返回某些内容,则需要将返回类型设置为异步任务。停止猜测,花点时间验证您提供的解决方案是否正确。
public async Task GetData()
        {
            return await Client.GetAsync("https://www.test.com/users");
        }