MapGet メソッドで ContentType を設定する

ペムノン
質問: MapGetでのContentType
ASP.NET Core のMapGetでContentTypeを設定したいです。どのようなコードを記述すればよいでしょうか?

はじめに

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

アクセス時のレスポンスを開発ツールで確認します。コードで指定した "application/json" がContent-Typeとなっていることが確認できます。
MapGet メソッドで ContentType を設定する:画像1

AuthorPortraitAlt
著者
iPentecのメインプログラマー
C#, ASP.NET の開発がメイン、少し前まではDelphiを愛用
作成日: 2025-02-01
Copyright © 1995–2025 iPentec all rights reserverd.