ASP.NET Core でシンプルなレスポンスを返すアプリケーションを作成する - Run メソッドの利用 - ASP.NET Core

ASP.NET Core でRunメソッドを利用してシンプルなレスポンスを返すアプリケーションを作成します。

概要

ASP.NET Coreを利用してシンプルなレスポンスを返すアプリケーションを作成します。アプリケーションがレスポンスを返すには Run メソッドを利用します。

プログラム例

事前準備

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

コード

Startup.cs コードを修正します。下記のコードを記述します。
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 SimpleMiddlewareRun
{
  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.Run(async context =>
      {
        await context.Response.WriteAsync("<html><body><div>Hello ASP.NET Core World!</div></body></html>");
      });
    }
  }
}

解説

下記のコードが追記したコードになります。Runメソッドの引数にデリゲートを与えます。今回のコードではラムダ式でデリゲートを記述しています。ラムダ式については以下の記事を参照してください。(参照:デリゲートとラムダ式の書き換え =>演算子の利用 (C#プログラミング))
デリゲート内ではデリゲートに与えられたContextオブジェクトのResponse オブジェクトのWriteAsyncメソッドを呼び出し、レスポンスのテキストを出力します。今回の例ではシンプルなHTMLのレスポンスを返しています。
  app.Run(async context =>
  {
    await context.Response.WriteAsync("<html><body><div>Hello ASP.NET Core World!</div></body></html>");
  });

実行結果

プロジェクトを実行します。Webブラウザが起動し下図の画面が表示されます。


アドレスバーでURLを変更してみます。アプリケーションルートURLの後ろに "/Penguin" を追加してアクセスします。アプリケーションルートのURLにアクセスしたときと同じ画面が表示されます。


さらに、アプリケーションルートURLの後ろに "/Duck?key=10" を追加してアクセスします。こちらもアプリケーションルートのURLにアクセスしたときと同じ画面が表示されます。アプリケーションルート以下のURLにアクセスした場合は同じ出力になる動作のようです。

別のコード例

レスポンスはJSON形式などのHTML以外のレスポンスを戻すこともできます。下記はJSONをレスポンスで返すコードの例です。
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 SimpleMiddlewareRun
{
  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.Run(async context =>
      {
        context.Response.ContentType = "application/json";
        await context.Response.WriteAsync("{\"ProductName\":\"Penguin Cookie\",\"price\":280}");
      });
    }
  }
}

実行結果

プロジェクトを実行します。Webブラウザが起動し下図の画面が表示されます。JSONが出力されていることが確認できます。


アプリケーションルート以下のURLを変更してアクセスした場合でも同じ出力が戻ることが確認できます。


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