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

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

概要

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

プログラム例

事前準備

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

コード

下記のコードを記述します。基本的には、ASP.NET Core Webアプリケーション作成時の雛型のコードそのままです。
Startup.cs
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 RootingEndpoint
{
  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.UseRouting();
      
      app.UseEndpoints(endpoints =>
      {
        endpoints.MapGet("/", async context =>
              {
            await context.Response.WriteAsync("Hello ASP.NET Core World EndPoint!");
          });
      });
    }
  }
}
Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

namespace RootingEndpoint
{
  public class Program
  {
    public static void Main(string[] args)
    {
      CreateHostBuilder(args).Build().Run();
    }

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(webBuilder =>
            {
              webBuilder.UseStartup<Startup>();
            });
  }
}

解説

下記のコードによりルーティングのミドルウェアを利用します。
  app.UseRouting();

ルーティングのエンドポイントの実装部分のコードが下記です。今回は "/" のアプリケーションルートのみにルーティングします。ルーティング先のエンドポイントでは、"Hello ASP.NETCore World EndPoint!" の文字列をレスポンスとして返す動作を実装しています。
  app.UseEndpoints(endpoints =>
  {
    endpoints.MapGet("/", async context =>
      {
        await context.Response.WriteAsync("Hello ASP.NET Core World EndPoint!");
      });
  });

実行結果

プロジェクトを実行します。Webブラウザが起動し下図の画面が表示されます。アプリケーションルートのURLが表示されるため、"Hello ASP.NETCore World EndPoint!" の出力が表示されることが確認できます。


(アプリケーションルートURL)/query のURLにアクセスします。ルーティングの設定がされていないURLのため、Not Found のHTTP 404エラーの表示になります。


ルーティングの機能を利用してWebアプリケーションにエンドポイントを実装できました。

著者
iPentecのメインプログラマー
C#, ASP.NET の開発がメイン、少し前まではDelphiを愛用
最終更新日: 2019-10-25
作成日: 2019-10-24
iPentec all rights reserverd.