Asp.net 如何在屏幕上显示Web API接收的图像

Asp.net 如何在屏幕上显示Web API接收的图像,asp.net,angular,Asp.net,Angular,我有一个图像,图像数据通过web api来自数据库。此图像的路径保存在DB的imagePath列中。然而,当我通过web api调用这些数据时,我只能得到这个路径值。所以,如果我想用这个路径显示一个图像,我会得到404错误。 我不明白如何在UI上显示这个图像。Angular在不同的端口上工作,后端也在不同的端口上工作。如果我使用后端url/端口获取图像,在搜索引擎优化方面就不好了。我怎样才能解决这个问题 我在后端使用C#&.NETCore3.1和Asp.NETWebAPI 汽车部件代码 getC

我有一个图像,图像数据通过web api来自数据库。此图像的路径保存在DB的imagePath列中。然而,当我通过web api调用这些数据时,我只能得到这个路径值。所以,如果我想用这个路径显示一个图像,我会得到404错误。 我不明白如何在UI上显示这个图像。Angular在不同的端口上工作,后端也在不同的端口上工作。如果我使用后端url/端口获取图像,在搜索引擎优化方面就不好了。我怎样才能解决这个问题

我在后端使用C#&.NETCore3.1和Asp.NETWebAPI

汽车部件代码

getCars(){
this.carService.getCars().subscribe(response => {
  this.cars = response.data;
  this.dataLoaded = true;
  this.setCoverImage(this.cars);
});
}  
getCarImages(){
      this.carImageService.getCarImages().subscribe(response => {
          this.carImages = response.data;
        })
      }


 setCoverImage(carList: Car[]){
     carList.forEach(item => {
       this.carImageService.getCarImagesById(item.carId).subscribe(response => {
         item.imagePath = "http://localhost:4200/" + response.data[0].imagePath;
       })
      })
    }
汽车图像服务代码

export class CarImageService {
  apiUrl = "https://localhost:44327/api/";
  constructor(private httpClient : HttpClient) { }

  getCarImages() : Observable<ListResponseModel<CarImage>>{
    let newPath = this.apiUrl + "carimages/getall";
    return this.httpClient.get<ListResponseModel<CarImage>>(newPath);
  }

  getCarImagesById(carId: number) : Observable<ListResponseModel<CarImage>>{
    let newPath = this.apiUrl + "carimages/getimagesbycarid?id=" + carId;
    return this.httpClient.get<ListResponseModel<CarImage>>(newPath);
  } 
}
导出类服务{
apiUrl=”https://localhost:44327/api/";
构造函数(私有httpClient:httpClient){}
getCarImages():可观察{
让newPath=this.apirl+“carimages/getall”;
返回此.httpClient.get(newPath);
}
getCarImagesById(carId:number):可观察{
让newPath=this.apiUrl+“carimages/getimagesbycard?id=“+carId;
返回此.httpClient.get(newPath);
} 
}
API输出


您可以在客户端应用程序中使用代理

我的项目示例:

{
  "context": [ "/images" ], 
  "target" : "http://localhost:5000", 
  "secure": false, 
  "changeOrigin": true, 
  "logLevel": "debug"
}

通过这种json代理配置,我可以从wwwroot目录下的images文件夹中获取文件。

我认为这不是一种安全或好的方法

  • 最好的解决方案是以字节数组的形式从API中获取图像

    var byteArrImg=File.ReadAllBytes(“images/13561.jpg”); var base64Img=Convert.ToBase64String(byteArrImg)

在客户端代码属性中,绑定Image标记的src属性以显示图像

setCoverImage(carList: Car[]){
     carList.forEach(item => {
       this.carImageService.getCarImagesById(item.carId).subscribe(response => {
         item.imagePath = response;
       })
      })
    }
在html中

<image
[src]="item.imagePath"
/>


您应该看看关于类似问题的其他问题:,@HereticMonkey谢谢您的评论。我是这个世界上的新手,很多时候我都找不到关于我的问题的任何东西。然而,我解释了一些关于这个的话题,但我不能解决这个问题。当我看到你的评论时,我也浏览了你的链接,但我想这些与我的问题无关。我用代理解决了这个问题。再次感谢。这可能比我的代码更好。我已经在学习这个有趣的世界,所以有时候我不知道哪种方式是最好的。我会记下来的,谢谢你的帮助。非常感谢你,我把你的建议和它对我的帮助都用上了。我是这个世界上的新手,有时为我找到解决方案有点困难。