用 WebApi 傳回圖片並嵌入<img/>
工作紀錄。How can I return Images from Web API in ASP.NET?
參考文件
開發環境
IDE: Visual Studio 2022
平台: .NET6
骨架: Blaozr Server App + Web API
CSS Framework: MudBlaozr v6.x
關鍵原碼
後端部份,利用 Web API 取得圖片,此圖片需有登入授權才能送回。
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Text;
namespace YourProject.Controllers;
[Route("api/[controller]")]
[ApiController]
[Authorize] //<--- 登入後才能看到圖片
public class ImageGateController : ControllerBase
{
[HttpGet("{id}")] //<--- 用 GET Method 讓 <img/>可直接使用圖片。
public IActionResult Get(string id)
{
// 直接送回圖片實體檔
if (id == "abc")
return PhysicalFile(@"C:\圖片\火拳.png", "image/png");
// 或以 BLOB 送回圖片檔
if (id == "foo")
{
FileInfo imgFile = new FileInfo(@"C:\圖片\妮可羅賓.jpg");
using var fs = imgFile.OpenRead();
byte[] imgBlob = new byte[fs.Length];
fs.Read(imgBlob, 0, imgBlob.Length);
return File(imgBlob, "image/jpeg");
}
// 不是核可的圖片不予送回。
return BadRequest();
}
}
前端部份,直接用 HTML 的 <img />
標籤取得圖片。注意在事前已登入該網站了。
@page "/"
<PageTitle>Index</PageTitle>
<MudPaper Class="pa-2 ma-2">
<MudText Typo=Typo.h5>登入後才能看到圖片</MudText>
<MudImage Src="api/imagegate/abc" Width="500" />
<MudImage Src="api/imagegate/foo" Width="500" />
</MudPaper>
Last updated