RazorPages で特定のURLで独自のレスポンスを実装する - MapGet メソッドの利用 - ASP.NET Core

RazorPages で特定のURLで独自のレスポンスを実装するコードを紹介します。

概要

RazorPagesでは、RazorPageの@pageディレクティブの設定でURLをRazorPageにルーティングできます。 しかし、RazorPageを作成せずに特定のURLのレスポンスを実装したい場合があります。 この記事では、RazorPagesアプリケーションで、MapGetメソッドを利用して、特定のURLのレスポンスを実装するコードを紹介します。

プログラム例

ASP.NET Coreアプリケーションを作成します。 手順はこちらの記事を参照してください。

コード

以下のコードを記述します。
Program.cs
using System.Text;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddRazorPages();
var app = builder.Build();

app.UseStaticFiles();
app.UseRouting();

app.UseEndpoints(endpoints =>
{
  endpoints.MapGet("/custom", async context =>
  {
    context.Response.StatusCode = 200;
    context.Response.ContentType = "text/plain";
    byte[] bytes = Encoding.UTF8.GetBytes("Custom Response");
    await context.Response.Body.WriteAsync(bytes);
    await context.Response.CompleteAsync();
  });
});

app.MapRazorPages();

app.Run();
Pages\Index.cshtml
@page
@model RazorPagesMapGet.Pages.IndexModel
@{
}
<html>
  <head>
    <title>TestPage</title>
  </head>
  <body>
    <h2>RazorPagesでのMapGetメソッド利用のデモ</h2>
    <p>Index.cshtml ページです。</p>
  </body>
</html>
Pages\Index.cshtml.cs
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;

namespace RazorPagesMapGet.Pages
{
    public class IndexModel : PageModel
    {
        public void OnGet()
        {
        }
    }
}

ファイルの配置は下図となります。

解説

トップレベルステートメント(top-level statements)にapp.UseEndpoints()メソッドを記述し、 引数にIEndpointRouteBuilderオブジェクト引数に取るデリゲートを与えます。
デリゲートの実装で、MapGetメソッドの呼び出しを記述します。
今回のコードでは正常なレスポンスコード200を返し、"Custom Response" の文字列を返します。
app.UseEndpoints(endpoints =>
{
  endpoints.MapGet("/custom", async context =>
  {
    context.Response.StatusCode = 200;
    context.Response.ContentType = "text/plain";
    byte[] bytes = Encoding.UTF8.GetBytes("Custom Response");
    await context.Response.Body.WriteAsync(bytes);
    await context.Response.CompleteAsync();
  });
});

実行結果

プロジェクトを実行します。
アプリケーションルートURLが開かれ、Index.cshtmlのRazroPageが表示されます。


Webブラウザで アプリケーションルートURL/custom のURLを開きます。下図の画面に変わります。ページにコードに記述した "Custom Response"の文字列が表示されています。


開発者ツールで確認します。
レスポンスコードが200であること、Content-Typeが"text/plain"であることが確認できます。


レスポンスのBodyに"Custom Response"が設定されていることも確認できます。


Razor PagesアプリケーションでMapGetメソッドを利用してレスポンスを返すことができました。

補足1: ラムダ式を使用しない記述

ラムダ式を利用しない場合は以下の記述になります。
Program.cs
using System.Text;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddRazorPages();
var app = builder.Build();

app.UseStaticFiles();
app.UseRouting();
app.UseEndpoints(MyBuilder);
app.MapRazorPages();

app.Run();


async void MyBuilder(IEndpointRouteBuilder ep)
{
  ep.MapGet("/custom", MyResponse);
}

async void MyResponse(HttpContext context) {
  context.Response.StatusCode = 200;
  context.Response.ContentType = "text/plain";
  byte[] bytes = Encoding.UTF8.GetBytes("Custom Response");
  await context.Response.Body.WriteAsync(bytes);
  await context.Response.CompleteAsync();
}

補足2

トップレベルステートメントを利用せず、MapRazorPages()メソッドを、UseEndpointsのデリゲート内に記述するコードです。
Program.cs
using System.Text;

namespace RazorPagesMapGetNTLS
{
  public class Program
  {
    public static void Main(string[] args)
    {
      var builder = WebApplication.CreateBuilder(args);
      builder.Services.AddRazorPages();
      var app = builder.Build();

      app.UseStaticFiles();
      app.UseRouting();

      app.UseEndpoints(endpoints =>
      {
        endpoints.MapGet("/custom", async context =>
        {
          context.Response.StatusCode = 200;
          context.Response.ContentType = "text/plain";
          byte[] bytes = Encoding.UTF8.GetBytes("Custom Response");
          await context.Response.Body.WriteAsync(bytes);
          await context.Response.CompleteAsync();
        });
        endpoints.MapRazorPages();
      });

      app.Run();
    }
  }
}
著者
iPentecのメインプログラマー
C#, ASP.NET の開発がメイン、少し前まではDelphiを愛用
最終更新日: 2024-01-28
作成日: 2024-01-28
iPentec all rights reserverd.