MapGet メソッドで ContentType 指定する場合には、context
オブジェクトのResponse.ContentType
プロパティを設定します。
以下のコードを記述します。
namespace SimpleMapGet
{
public class Program
{
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.MapGet("/", () => "Hello World!");
app.MapGet("/getdata", async context =>
{
// レスポンスヘッダーに Content-Type を設定
context.Response.ContentType = "application/json; charset=utf-8";
string data = "[{\"name\":\"ぺんぎんクッキー\",\"price\":285,\"weight\":\"45g\"},{\"name\":\"らくだキャラメル\",\"price\":180,\"weight\":\"20g\"}]";
await context.Response.WriteAsync(data);
});
app.Run();
}
}
}
以下のコードで、MapGetでアクセスした際のレスポンスのContentTypeを設定しています。
context.Response.ContentType = "application/json; charset=utf-8";
プロジェクトを実行します。
以下のURLにアクセスします。
(アプリケーションルートURL)/getdata