繁体   English   中英

同步运行HttpRequest C#

[英]Running HttpRequest synchronously C#

我有两个功能-我们称它们为A和B。

  • B是将HTTP请求发送到服务器并返回字典的功能。
  • A是一个调用B的函数,然后在几个不同的代码行中使用它返回的Dictionary。

我试图使功能A等待功能B的结果。 以及在函数A末尾的解析以等待HTTP响应。

由于HttpClient需要Async工作,因此我无法弄清楚该如何完成,而我需要避免它在不同的线程上运行,因为我需要整个代码来等待响应。

我试过使用Task返回值,将函数B转换为类,并在响应变量中使用await,而不是。 无法完成=(

protected async Task<Dictionary<string, string>> B()
{
    using (var httpClient = new HttpClient())
    {
        using (var request = new HttpRequestMessage(new HttpMethod("GET"), "https://example.com/wp-json/wc/v3/products"))
        {
            var base64authorization = Convert.ToBase64String(Encoding.ASCII.GetBytes("CC"));
            request.Headers.TryAddWithoutValidation("Authorization", $"Basic {base64authorization}");

            var response = await httpClient.SendAsync(request);
            var contents = await response.Content.ReadAsStringAsync();

            dynamic attributes = JsonConvert.DeserializeObject(contents);
            Dictionary<string, string> existing = new Dictionary<string, string>();
            foreach (var attr in attributes)
            {
                existing.Add(attr.name, "" + attr.id);
            }
            return existing;
        }
    }
}

和功能A:

void A(){
    Dictionary<string, string> existingAttr = B();
    // Then Does some code with existingAttr
}

我得到的错误是

System.Collections.Generic.Dictionary.Add(string,string)'ilegal arguments“

可能是因为当时的回应还不完整。

预先感谢大家! 🙃

这个:

Dictionary<string, string> existingAttr = B();

不起作用,因为B()返回Task<Dictionary<string, string>> ,而不仅仅是Dictionary<string, string>

由于这是ASP.NET,因此没有理由使其同步。 另外,这只会带来麻烦。 它会。 不要这样

使一切async

async Task A(){
     Dictionary<string, string> existingAttr = await B();
     // Then Does some code with existingAttr
}

使任何调用A() async并一直使用await A()直到Controller。

更新:首先,您的“非法参数”错误对我来说没有意义,因为通常会在编译时抛出这种错误。 但是我靠近了一下,注意到了这一点:

dynamic attributes = JsonConvert.DeserializeObject(contents);

因为attributesdynamic ,所以在实际运行该代码之前,编译器不知道它的实际类型。 因此,您的异常发生在这里:

existing.Add(attr.name, "" + attr.id);

因为您要喂的东西不是string 由于连接,表达式"" + attr.id可能会以字符串形式出现。 但是attr.name不会。 当您使用JsonConver.DeserializeObject获取dynamic对象时,属性的实际类型是JValue而不是string

可以使用.ToString()

existing.Add(attr.name.ToString(), attr.id.ToString());

但这是一个很好的例子,说明为什么最好为数据创建一个实际的类:

public class MyAttributes {
    public string Name {get; set;}
    public string Id {get; set;}
}

并反序列化为该类型:

var attributes = JsonConvert.DeserializeObject<List<MyAttributes>>(contents);

这样,这些错误会在编译时被捕获,并且以后您不会再收到令人讨厌的惊喜。

您可以使用await关键字。 等待将在方法B的执行中插入一个暂停点,直到等待的任务完成为止。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM