ASP.NET Core Web アプリケーションでルーティング機能を利用してPOSTのエンドポイントを作成する - ASP.NET Core

ASP.NET Core Web アプリケーションでPOSTによるエンドポイントの作成をするコードを紹介します。

概要

ASP.NET Core Web アプリケーションでルーティング機能を利用してエンドポイントを作成すると高度な設定ができるようになります。この記事では、ASP.NET Core Webアプリケーションでルーティング機能を利用し、POST処理に対応したエンドポイントを作成するコードを紹介します。POSTのエンドポイントを作成する場合は、IEndpointRouteBuilder の MapPostメソッドを利用します。

プログラム例

事前準備

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

静的ファイルの作成

wwwrootフォルダを作成して、POST元の静的HTMLファイルを作成します。


今回は test.html ファイルを作成します。test.html ファイルの内容は下記のとおりです。

test.html
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title></title>
</head>
<body>
    <form method="post" action="/operation/send">
        <div>value<input name="key" type="text" /></div>
        <input type="submit" value="POST" />
    </form>
</body>
</html>

コード

下記のコードを記述します。基本的には、Startup.csを修正します。
test.html
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace RootingEndpointPost
{
  public class Startup
  {
    // This method gets called by the runtime. Use this method to add services to the container.
    // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
    public void ConfigureServices(IServiceCollection services)
    {
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
      if (env.IsDevelopment()) {
        app.UseDeveloperExceptionPage();
      }

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

      app.UseEndpoints(endpoints =>
      {
        endpoints.MapPost("/operation/send", async context =>
        {
          string postvalue = context.Request.Form["key"];
          await context.Response.WriteAsync("Hello ASP.NET Core World!:"+ postvalue);
        });
      });
    }
  }
}

解説

Configure メソッドのUseStaticFilesメソッドの呼び出しで静的ファイルにアクセスできる状態にします。
  app.UseStaticFiles();

UseRoutingメソッドの呼び出しでエンドポイントのルーティングができる状態にします。
  app.UseRouting();

エンドポイントの実装コードです。MapPostメソッドを呼び出しPOSTのエンドポイントを追加します。エンドポイントのパターンには /operation/send を与えます。実装部分のコードでは"Hello ASP.NET Core World!:"のメッセージと、POSTで渡された値のkeyの項目の値を返します。
  app.UseEndpoints(endpoints =>
  {
    endpoints.MapPost("/operation/send", async context =>
    {
      string postvalue = context.Request.Form["key"];
      await context.Response.WriteAsync("Hello ASP.NET Core World!:"+ postvalue);
    });
  });

実行結果

プロジェクトを実行します。Webブラウザが開きアプリケーションルートのURLが表示されます。今回のコードではアプリケーションのルートのパターンを処理するロジックは実装されていないため、404 Not Foundエラーが表示されます。


Webブラウザのアドレスバーで (アプリケーションルートURL)/test.html にアクセスします。wwwrootフォルダに配置したtest.htmlのページが表示されます。


テキストボックスに入力します。今回は "Penguin" の文字列を入力しました。入力ができたらテキストボックスの下の[POST]ボタンをクリックします。


URLが (アプリケーションルートURL)/operation/send に変わります。POST先のページに遷移しました。画面には "Hello ASP.NET Core World!:Penguin" の文字列が表示されています。MapPostメソッドで実装したメッセージと、POSTで送信したテキストが表示できていることが確認できます。


以上の手順でPOSTのエンドポイントが作成できました。
著者
iPentecのメインプログラマー
C#, ASP.NET の開発がメイン、少し前まではDelphiを愛用
最終更新日: 2019-10-27
作成日: 2019-10-27
iPentec all rights reserverd.