当getasync只调用一次c#ApicController时,它会被调用两次

当getasync只调用一次c#ApicController时,它会被调用两次,c#,httpclient,asp.net-apicontroller,C#,Httpclient,Asp.net Apicontroller,你好,我遇到了一个非常有趣的bug,我不明白为什么会发生这种情况。我通过httpclient的GetAsync方法从另一个项目中调用GetAllDocuments()方法到api。但是问题是GetAllDocuments返回,然后它会再次被调用!GetAsync在GetAllDocuments返回两次后返回结果 以下是调用方法: public static async Task<Document> GetAllDocuments() { try

你好,我遇到了一个非常有趣的bug,我不明白为什么会发生这种情况。我通过httpclient的GetAsync方法从另一个项目中调用GetAllDocuments()方法到api。但是问题是GetAllDocuments返回,然后它会再次被调用!GetAsync在GetAllDocuments返回两次后返回结果

以下是调用方法:

public static async Task<Document> GetAllDocuments()
    {
        try
        {

            var response =  _client.GetAsync("api/documents/GetAllDocuments").Result;
            response.Content.LoadIntoBufferAsync().Wait();
            response.EnsureSuccessStatusCode();
            return await response.Content.ReadAsAsync<Document>(new[] { new JsonMediaTypeFormatter() }); ;
            // Return the URI of the created resource.
        }
        catch (Exception ex)
        {
            return null;
        }
    }

为什么要用.Result阻止第一个异步调用并等待另一个呢?别胡闹!哦,
Wait()
@Crowcoder也是如此,我想api仍然会被调用两次。那么您的建议中的代码应该是什么样的呢?只需使用
Wait
,就像使用
ReadAsAsync
一样,然后删除
。Result
Wait()
。如果你在控制台应用程序之外这样做,那你就是做错了。@Crowcoder按照你的建议做了,但事情是一样的:var response=wait_client.GetAsync(“api/documents/GetAllDocuments”);response.EnsureSuccessStatusCode();return wait response.Content.ReadAsAsync(new[]{new JsonMediaTypeFormatter()});我没说那是你的解决方案,但你确实需要解决它。这真的是你的控制器代码吗?它不应该编译,因为您返回的是任务,但签名是列表。
[HttpGet]
    public List<Document> GetAllDocuments()
    {
        lock (_lock)
        {
            _documentsRepository = DocumentsRepository.Instance;
            var result = _documentsRepository.GetDocuments();

            return result;
        }
    }
public static class WebApiConfig
{
    private static HttpSelfHostServer _server;

    public static void Run(string port)
    {
        var config = new HttpSelfHostConfiguration($"http://localhost:{port}");//"http://localhost:8080");

        config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();

        config.Routes.MapHttpRoute(
            "API Default", "api/{controller}/{id}",
            new { id = RouteParameter.Optional });

        config.Routes.MapHttpRoute(
            "newdocument", "api/documents/newdocument/{document}",new { document = RouteParameter.Optional });

        config.Routes.MapHttpRoute(
            "GetAllDocuments", "api/documents/GetAllDocuments/");

        config.MaxReceivedMessageSize = int.MaxValue;;
        config.MaxBufferSize = int.MaxValue;
        _server = new HttpSelfHostServer(config);
        _server.OpenAsync();

    }

    public static void Stop()
    {
        _server?.CloseAsync();
    }
}