這是我的示例命令列應用程式。我正在使用帶有 dot-net 6 的 Windows 10。
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using System.IO;
var app = WebApplication.Builder();
app.MapGet("/", MyGet);
byte[] MyGet(HttpContext context)
{
context.Response.ContentType="image/png";
return File.ReadAllBytes("MyImage.png");
}
app.Run();
當我運行它并瀏覽到服務器時,我得到的是 JSON/Base64 格式的位元組,而不是回傳的 PNG 影像。
為 MyGet 使用字串回傳型別很高興將純文本或 HTML 發送到客戶端。我怎樣才能發送任意位元組呢?
uj5u.com熱心網友回復:
如果要將影像作為檔案下載發送:
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.MapGet("/", MyGet);
async Task MyGet(HttpContext context)
{
context.Response.ContentType="image/png";
context.Response.Headers.Add("content-disposition", $"attachment; filename=test");
await context.Response.Body.WriteAsync(File.ReadAllBytes("MyImage.png"));
//await context.Response.SendFileAsync(new FileInfo("MyImage.png").FullName);
}
app.Run();
uj5u.com熱心網友回復:
context.Response.Body.WriteAsync(someBytes);
(我很感謝用戶rawel指出我這個方向。我Response.Body.Write在發布我的問題之前嘗試過,但這沒有用,一個錯誤,抱怨不允許同步寫入。在我的情況下,發送回應是我的最后一件事get 函式可以,所以讓異步操作保持打開狀態沒有問題。)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/471498.html
上一篇:如何驗證HTTP回應?
