【问题标题】:cannot convert from system.threding.Tasks .task<byte[]> to byte[]无法从 system.threading.Tasks .task<byte[]> 转换为 byte[]
【发布时间】:2021-08-26 02:22:19
【问题描述】:

我是 C# 的新手并做出反应。我正在使用以下方法将图像 url 转换为字节

return Convert.ToBase64String(bytes);

但我收到一个错误提示

无法从System.Threading.Tasks.Task&lt;byte[]&gt; 转换为byte[]

这是方法:

[HttpGet]      
[Route("GetImages")]
public  IHttpActionResult GetImages()
{    
    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
    WebProxy myproxy = new WebProxy("corpproxy1.tatasteel.com", 80);
        myproxy.BypassProxyOnLocal = false;
    //myproxy.UseDefaultCredentials = true;    

    HttpClientHandler handler = new HttpClientHandler()
    {
        Proxy = myproxy
    };

    using (var client = new HttpClient(handler))
    {
        var bytes = 
             client.GetByteArrayAsync("https://firebasestorage.googleapis.com/v0/b/tsl-coil- 
        qlty-monitoring-dev.appspot.com/o/1a60ce3b-eddf-4e72-b2af-b6e99873e926? 
        alt=media&token=61399a02-1009-4bb9-ad89-d1235df900e4");
           
        return Convert.ToBase64String(bytes);
    }    
}

如何纠正这个错误?

【问题讨论】:

标签: c# image-processing task


【解决方案1】:

GetByteArrayAsync 是一个异步方法,它返回一个任务。您需要等待任务以获取返回值。为了等待它,动作方法必须是异步的。

[HttpGet]
[Route("GetImages")]
public async Task<IHttpActionResult> GetImages()
{
    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
    WebProxy myproxy = new WebProxy("corpproxy1.tatasteel.com", 80);
    myproxy.BypassProxyOnLocal = false;
    HttpClientHandler handler = new HttpClientHandler()
    {
        Proxy = myproxy
    };
    using (var client = new HttpClient(handler))
    {
        var bytes = await client.GetByteArrayAsync("https://firebasestorage.googleapis.com/v0/b/tsl-coil- 
             qlty-monitoring-dev.appspot.com/o/1a60ce3b-eddf-4e72-b2af-b6e99873e926? 
             alt=media&token=61399a02-1009-4bb9-ad89-d1235df900e4");
           
        return Convert.ToBase64String(bytes);
    }
}

【讨论】:

  • 我这样做了 现在它的显示不能隐式地将类型字符串转换为 'System.web.Http.IHttpAction 结果以返回 Convert.ToBase64String(bytes);
  • 公共异步任务 GetImages
  • @sambit return Ok(Convert.ToBase64String(bytes));
【解决方案2】:

由于GetByteArrayAsync返回Task,所以必须等待任务完成:

var bytes = client.GetByteArrayAsync("https://firebasestorage.googleapis.com/v0/b/tsl-coil- 
    qlty-monitoring-dev.appspot.com/o/1a60ce3b-eddf-4e72-b2af-b6e99873e926? 
    alt=media&token=61399a02-1009-4bb9-ad89-d1235df900e4").Result

var bytes = await client.GetByteArrayAsync("https://firebasestorage.googleapis.com/v0/b/tsl-coil- 
    qlty-monitoring-dev.appspot.com/o/1a60ce3b-eddf-4e72-b2af-b6e99873e926? 
    alt=media&token=61399a02-1009-4bb9-ad89-d1235df900e4")

第二种方式通常比第一种更好,它不会阻塞线程

【讨论】:

  • 我不会鼓励 OP 使用.Result。如果他需要同步调用异步方法,那么更喜欢.GetAwaiter().GetResult()Reference
猜你喜欢
  • 2016-01-29
  • 2018-09-05
  • 2020-06-11
  • 2013-02-10
  • 1970-01-01
  • 1970-01-01
  • 2021-06-18
  • 2011-06-08
  • 1970-01-01
相关资源
最近更新 更多