C# 如何使图像API的Get请求工作?
我不知道问题出在哪里,所以我只给你一些背景知识: 我的图像Api获取方法:C# 如何使图像API的Get请求工作?,c#,asp.net-core,mvvm,uwp,dotnet-httpclient,C#,Asp.net Core,Mvvm,Uwp,Dotnet Httpclient,我不知道问题出在哪里,所以我只给你一些背景知识: 我的图像Api获取方法: [Route("{name}", Name = "GetImageByName")] public IActionResult Get(string name) { string imagePath = GetImagePath(); string fileName = $"{imagePath}\\{name}"; if (!System.IO.File
[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);
}
}
这在《邮递员》中很管用:
获取请求:
这将返回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;
}
公共异步任务GetImage(字符串imageStringName)
{
var uri=新的uri(“https://picsum.photos/200/300");
BitmapImage BitmapImage=新的BitmapImage();
var rass=RandomAccessStreamReference.CreateFromUri(uri);
使用(irandomaccesstream=await rass.OpenReadAsync())
{
bitmapImage.SetSource(流);
}
返回位图图像;
}
这适用于外部伪api,但不适用于本地主机api
所以我最后的问题是:为什么最后一个解决方案不能从我的API中获取图像?为什么正常的httpClient.GetAsync(Uri)不能工作?从api获取图像的最佳解决方案是什么?UWP默认情况下无法访问
localhost
。检查的“环回”部分,了解如何启用它。什么是异常?消息:“发生了一个或多个错误。(发送请求时出错。)”字符串。System.Exception{System.AggregateException}。和InnerException:System.Exception{System.Net.Http.HttpRequestException}首先,我不明白为什么会得到AggregateException。您不是在整个呼叫链中等待吗?第二,这是没有帮助的。描述错误在聚合中的某个地方。您将需要或展平它以获得具体发生的情况。您可能只需要设置适当的Accept标头。