【发布时间】:2020-07-22 01:06:59
【问题描述】:
我不知道问题是什么,所以我只是给你一些背景:
我的 Image Api GET 方法:
[Route("{name}", Name = "GetImageByName")]
public IActionResult Get(string name)
{
string imagePath = GetImagePath();
string fileName = $"{imagePath}\\{name}";
if (!System.IO.File.Exists(fileName))
return NotFound();
try
{
var image = System.IO.File.ReadAllBytes(fileName);
string extension = new FileInfo(fileName).Extension.Substring(1);
return File(image, $"image/{extension}");
}
catch (ArgumentException ex)
{
return BadRequest(ex.Message);
}
catch (PathTooLongException ex)
{
return StatusCode(414, ex.Message);
}
catch (DirectoryNotFoundException ex)
{
return NotFound(ex.Message);
}
catch (UnauthorizedAccessException)
{
return Unauthorized();
}
catch (FileNotFoundException ex)
{
return NotFound(ex.Message);
}
catch (NotSupportedException ex)
{
return StatusCode(415, ex.Message);
}
catch(Exception ex)
{
return StatusCode(500, ex.Message);
}
}
这在邮递员中工作正常: 获取请求:https://localhost:44355/api/Images/Sheet1.png 这将返回 200 OK 和图像
但使用 .net.http httpclient 则无法正常工作:
var uri = new Uri("https://localhost:44355/api/Images/Sheet1.png");
var response = await _httpClient.GetAsync(uri); //Not working and throws exception
我也尝试过这样从我的 API 加载图像:
public async Task<BitmapImage> GetImage(string imageStringName)
{
var uri = new Uri("https://picsum.photos/200/300");
BitmapImage bitmapImage = new BitmapImage();
var rass = RandomAccessStreamReference.CreateFromUri(uri);
using (IRandomAccessStream stream = await rass.OpenReadAsync())
{
bitmapImage.SetSource(stream);
}
return bitmapImage;
}
这适用于外部虚拟 api,但不适用于我的 localhost api。
所以我的最后一个问题是:为什么最后一个解决方案不能从我的 API 获取图像?为什么正常的 _httpClient.GetAsync(Uri) 不能正常工作?从 api 获取图像的实际最佳解决方案是什么?
【问题讨论】:
-
有什么异常?
-
消息:“发生一个或多个错误。(发送请求时发生错误。)”字符串。 System.Exception {System.AggregateException}。和 InnerException:System.Exception {System.Net.Http.HttpRequestException}
-
首先,我不明白您为什么会收到 AggregateException。您不是在整个呼叫链中
awaiting 吗?其次,这没有帮助。描述性错误在聚合中的某个地方。您将需要to handle each exception 或将其展平以获取具体发生的情况。您可能只需要设置适当的 Accept 标头。
标签: c# asp.net-core mvvm uwp dotnet-httpclient