OWIN を使用して ASP.NET Web API をセルフホストする

このチュートリアルでは、OWIN を使用して Web API フレームワークをセルフホストし、コンソール アプリケーションで ASP.NET Web API をホストする方法について説明します。

Open Web Interface for .NET (OWIN) は、.NET Web サーバーと Web アプリケーションの間の抽象化を定義します。 OWIN はサーバーから Web アプリケーションを切り離します。そのため、OWIN は IIS 外部の独自のプロセスで Web アプリケーションをセルフホストするのに最適です。

チュートリアルで使用するソフトウェアのバージョン

Note

このチュートリアルの完全なソース コードが github.com/aspnet/samples にあります。

コンソール アプリケーションを作成する

[ファイル] メニューの [新規作成] で、[プロジェクト] を選択します。 [インストール済み] から、[Visual C#][Windows デスクトップ] を選択し、[コンソール アプリ (.Net Framework)] を選択します。 プロジェクトに "OwinSelfhostSample" という名前を付け、[OK] を選択します。

Screenshot of the 'create new project' dialog box, showing the menu options to select Windows Desktop then Console App from the dropdown list.

Web API と OWIN パッケージを追加する

[ツール] メニューで、[NuGet パッケージ マネージャー] を選択し、[パッケージ マネージャー コンソール] を選択します。 [パッケージ マネージャー コンソール] ウィンドウで、次のコマンドを入力します。

Install-Package Microsoft.AspNet.WebApi.OwinSelfHost

これにより、WebAPI OWIN セルフホスト パッケージと必要なすべての OWIN パッケージがインストールされます。

Screenshot of the package manager console, showing licensing information, followed by P M > at the end, signaling where to type the command.

セルフホスト用に Web API を構成する

ソリューション エクスプローラーでプロジェクトを右クリックし、[追加] / [クラス] を選択して新しいクラスを追加します。 クラスに Startup という名前を付けます。

Screenshot of the solution explorer dialog box menu, showing the steps to follow for adding a class to the project.

このファイル内のすべての定型コードを次のように置き換えます。

using Owin; 
using System.Web.Http; 

namespace OwinSelfhostSample 
{ 
    public class Startup 
    { 
        // This code configures Web API. The Startup class is specified as a type
        // parameter in the WebApp.Start method.
        public void Configuration(IAppBuilder appBuilder) 
        { 
            // Configure Web API for self-host. 
            HttpConfiguration config = new HttpConfiguration(); 
            config.Routes.MapHttpRoute( 
                name: "DefaultApi", 
                routeTemplate: "api/{controller}/{id}", 
                defaults: new { id = RouteParameter.Optional } 
            ); 

            appBuilder.UseWebApi(config); 
        } 
    } 
}

Web API コントローラーを追加する

次に、Web API コントローラー クラスを追加します。 ソリューション エクスプローラーでプロジェクトを右クリックし、[追加] / [クラス] を選択して新しいクラスを追加します。 クラスに ValuesController という名前を付けます。

このファイル内のすべての定型コードを次のように置き換えます。

using System.Collections.Generic;
using System.Web.Http;

namespace OwinSelfhostSample 
{ 
    public class ValuesController : ApiController 
    { 
        // GET api/values 
        public IEnumerable<string> Get() 
        { 
            return new string[] { "value1", "value2" }; 
        } 

        // GET api/values/5 
        public string Get(int id) 
        { 
            return "value"; 
        } 

        // POST api/values 
        public void Post([FromBody]string value) 
        { 
        } 

        // PUT api/values/5 
        public void Put(int id, [FromBody]string value) 
        { 
        } 

        // DELETE api/values/5 
        public void Delete(int id) 
        { 
        } 
    } 
}

OWIN ホストを起動し、HttpClient を使用して要求を行う

Program.cs ファイル内のすべての定型コードを次のように置き換えます。

using Microsoft.Owin.Hosting;
using System;
using System.Net.Http;

namespace OwinSelfhostSample 
{ 
    public class Program 
    { 
        static void Main() 
        { 
            string baseAddress = "http://localhost:9000/"; 

            // Start OWIN host 
            using (WebApp.Start<Startup>(url: baseAddress)) 
            { 
                // Create HttpClient and make a request to api/values 
                HttpClient client = new HttpClient(); 

                var response = client.GetAsync(baseAddress + "api/values").Result; 

                Console.WriteLine(response); 
                Console.WriteLine(response.Content.ReadAsStringAsync().Result); 
                Console.ReadLine(); 
            } 
        } 
    } 
 }

アプリケーションの実行

アプリケーションを実行するには、Visual Studio で F5 キーを押します。 出力は次のようになります。

StatusCode: 200, ReasonPhrase: 'OK', Version: 1.1, Content: System.Net.Http.StreamContent, Headers: 
{ 
  Date: Tue, 09 Jul 2013 18:10:15 GMT 
  Server: Microsoft-HTTPAPI/2.0 
  Content-Length: 19 
  Content-Type: application/json; charset=utf-8 
} 
["value1","value2"]

Screenshot of the console, showing the status code and information for the application as it's running.

その他のリソース

プロジェクト Katana の概要

Azure worker ロールで ASP.NET Web API をホストする