📚

常駐アプリでHTTPリクエストを受けて返す(OWIN Self-Host + Web API 2 + log4net)

に公開

【.NET Framework 4.8】常駐アプリでHTTPリクエストを受けて返す(OWIN Self-Host + Web API 2 + log4net)

.NET Framework 4.8 で動く 常駐プロセスとして、HTTP リクエストを受けて JSON を返す最小構成です。
IIS や Windows サービスを使わず、自プロセス内で Web API をホストします(OWIN Self-Host / HttpListener)。

  • 目的:.NET Framework 4.8 の exe を常駐させ、HTTP で「ping」「shutdown」などの API を提供する
  • 例外:初期起動に失敗したら終了してOK、起動後のリクエスト処理の例外は log4net に記録して 500 を返し、プロセスは継続する

Microsoft のチュートリアルでは、OWIN を使って Web API を **IIS の外(自プロセス)**でセルフホストできることが説明されています。 citeturn7search0turn7search3
また、Microsoft.AspNet.WebApi.OwinSelfHost は OWIN HttpListener サーバーで「自プロセス内ホスト」を実現するパッケージであることが NuGet ページに明記されています。


1. 全体構成(ファイル一覧)

このサンプルは次の 9ファイルで構成されています(相対パス表記)。

  • Program.cs … 起動・停止(常駐)と log4net 初期化、OWIN ホスト開始
  • Startup.cs … Web API のルーティング・例外ハンドラ登録
  • ApiEndpointsController.cs … API エンドポイント(個別に [Route("...")] でパス定義)
  • Logging/Log4NetExceptionLogger.cs … リクエスト処理中の例外ログ(Web API の例外ログ機構)
  • Logging/Log4NetExceptionHandler.cs … 例外発生時の HTTP 応答(500 JSON)を統一
  • log4net.xml … log4net 設定(RollingFileAppender)
  • App.config … アプリ設定(このサンプルでは log4net の設定本体は外部 xml)
  • packages.config … NuGet 参照
  • ptest.csproj … .NET Framework 4.8 / 出力設定(WinExe)/ log4net.xml の出力コピー等

2. なぜ OWIN Self-Host(HttpListener)なのか

  • IIS を不要にできる(自分の exe の中で HTTP を待ち受けられる) citeturn7search0
  • ルーティングは Web API 2 の Attribute Routing で、Controller 名に依存せずに URL を固定できる
    (このサンプルは「全部デフォルト以外」で [Route("...")] を個別に書く)

3. URL(パス)はどこで分かるのか?

Controller の各メソッドに付いている [Route("...")] が、そのまま URL のパスです。
たとえば ApiEndpointsController.cs のこの行:

  • [Route("api/v1/ping")] → http://localhost:5005/api/v1/ping
  • [Route("api/v1/shutdown")] → http://localhost:5005/api/v1/shutdown

Controller クラス名(例:ApiEndpointsController)は、この構成では URL 生成に使いません。
URL は Route 属性だけで決まります(このサンプルはその方針)。


4. 起動後に例外が起きても「プロセスを生かす」設計

4.1 何が「プロセスを殺す」のか

  • リクエスト処理中の例外(Controller 内など)は、Web API のパイプラインで捕捉できれば 500 を返して継続できます。
  • 一方、未処理例外がプロセス外まで抜けるとプロセス終了になり得るため、Program.cs で
    • AppDomain.CurrentDomain.UnhandledException
    • TaskScheduler.UnobservedTaskException
      をログに落としています。

4.2 Web API 側(リクエスト処理中)の例外を log4net に落とす

Web API 2 には例外ログ・例外ハンドラ拡張点(IExceptionLogger / ExceptionLogger、ExceptionHandler)があります。
このサンプルではそれを使い、Controller 側で try/catch を全面に散らさず、一箇所で

  • 例外ログ(log4net)
  • 500 応答(JSON)
    を統一しています。

5. 実行時の注意:URL 予約(URLACL)が必要な場合

OWIN Self-Host は HttpListener を使います。
環境によっては、非管理者で待ち受ける URL に対して URL 予約が必要です。

Microsoft の add urlacl(URL 予約)ドキュメントでは、非管理者ユーザー向けに URL を予約するコマンドであると説明されています。

例(管理者権限のコマンドプロンプトで):

netsh http add urlacl url=http://localhost:5005/ user=Users

user= の指定は環境に合わせてください(Users / DOMAIN\UserName など)。
予約済みの確認は netsh http show urlacl です。


6. 動作確認(REST クライアント)

どの REST クライアントでも OK です(Postman / curl / Talend API Tester など)。
最低限の入力例:

GET ping

  • Method: GET
  • URL: http://localhost:5005/api/v1/ping

POST shutdown(JSON)

  • Method: POST
  • URL: http://localhost:5005/api/v1/shutdown
  • Headers:
    • Content-Type: application/json
  • Body(raw / JSON):
{"Reason":"manual stop"}

7. パフォーマンスの目安(「実用に耐える」条件の考え方)

同時クライアント数の“上限値”は、ハードウェア性能・同時アクセス形状・各 API がやる処理(I/O の重さ)・ログ出力量で決まるため、コードだけで「N まで確実」と断言はできません。

ただし、この構成(OWIN Self-Host + Web API 2)は 自プロセス内で軽量に動き、一般に次の条件を満たすほど安定しやすいです。

  • 各リクエストが短時間で完了する(重い処理はキューイング/別スレッドに逃がす)
  • Controller 内で長時間ブロックしない
  • ログが過剰に出ない(I/O が詰まらない)

実機で確認するなら、**負荷テストで “同時数” と “応答時間”**を測るのが最短です。
(例:bombardier / wrk / ab 相当で GET /api/v1/ping を並列で叩き、p95 応答時間を見る)


付録:ソースコード

以下は 相対パス/ファイル名付きで、アップロードされた内容をそのまま掲載しています。


Program.cs

using log4net;
using log4net.Config;
using Microsoft.Owin.Hosting;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ptest
{
    internal static class Program
    {
        // ★ ここが「ベースURL(host/port)」です
        //   [Route("api/v1/ping")] などは、この後ろに付きます。
        private const string BaseAddress = "http://localhost:5005/";

        // 例外用ログ(log4net.config の root/appender に流れる)
        private static readonly ILog Log = LogManager.GetLogger(typeof(Program));

        [STAThread]
        private static int Main()
        {
            // 1) log4net 初期化(外部ファイル + 監視)
            Directory.CreateDirectory("logs");
            XmlConfigurator.ConfigureAndWatch(new FileInfo("log4net.xml"));

            // 2) 未処理例外(プロセス外に逃げる例外)を捕まえる
            AppDomain.CurrentDomain.UnhandledException += (_, e) =>
            {
                var ex = e.ExceptionObject as Exception;
                Log.Fatal("AppDomain.UnhandledException", ex);
            };

            TaskScheduler.UnobservedTaskException += (_, e) =>
            {
                Log.Error("TaskScheduler.UnobservedTaskException", e.Exception);
                e.SetObserved();
            };

            try
            {
                using (WebApp.Start<Startup>(url: BaseAddress))
                {
                    //Log("Started: " + BaseAddress);
                    Log.Info("Started: " + BaseAddress);

                    // 常駐:Shutdown が来て AppLifetime.RequestStop() が呼ばれるまで待つ
                    AppLifetime.Token.WaitHandle.WaitOne();

                    //Log("Stop requested.");
                    Log.Info("Stop requested.");
                }

                //Log("Stopped.");
                Log.Info("Stopped.");
                return 0;
            }
            catch (Exception ex)
            {
                //Log("FATAL: " + ex);
                // 初期起動失敗はログ出して終了でOK、という要件
                SafeFatal("FATAL (Main startup)", ex);

                return 1;
            }
        }

        private static void SafeFatal(string message, Exception ex)
        {
            try
            {
                Log.Fatal(message, ex);
            }
            catch
            {
                // log4net 初期化前に落ちた場合の最後の保険
                try
                {
                    var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "fallback_fatal.log");
                    File.AppendAllText(path, $"{DateTime.Now:O} {message}\n{ex}\n", Encoding.UTF8);
                }
                catch { }
            }
        }

        //private static readonly object _logLock = new object();
        //
        //private static void Log(string message)
        //{
        //    try
        //    {
        //        var pid = Process.GetCurrentProcess().Id;
        //        var line = $"{DateTime.Now:yyyy-MM-dd HH:mm:ss.fff} [{pid}] {message}{Environment.NewLine}";
        //        var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "resident_app.log");

        //        lock (_logLock)
        //        {
        //            File.AppendAllText(path, line, Encoding.UTF8);
        //        }
        //    }
        //    catch
        //    {
        //        // ログ書けなくても落とさない
        //    }
        //}
    }
}


Startup.cs

using Owin;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.Http.ExceptionHandling;
using System.Web.UI.WebControls;

namespace ptest
{
    internal class Startup
    {
        // Startup クラスは WebApp.Start<Startup>() から呼ばれる(Learn の構成):contentReference[oaicite:5]{index=5}
        public void Configuration(IAppBuilder appBuilder)
        {
            var config = new HttpConfiguration();


            // ★ 属性ルーティング有効化(必須)
            config.MapHttpAttributeRoutes();

            //// /ping, /request, /shutdown のように「/{controller}」で受ける
            //config.Routes.MapHttpRoute(
            //    name: "DefaultApi",
            //    routeTemplate: "{controller}/{id}",
            //    defaults: new { id = RouteParameter.Optional }
            //);
            //// 既存のデフォルト(例:/shutdown や /ping を controller 名で受ける)
            //config.Routes.MapHttpRoute(
            //    name: "Default",
            //    routeTemplate: "{controller}"
            //);

            // ★リクエスト中の例外を log4net に出す(ログ)
            config.Services.Add(typeof(IExceptionLogger), new Logging.Log4NetExceptionLogger());

            // ★リクエスト中の例外を握りつぶして 500 を返す(プロセスを殺さない)
            config.Services.Replace(typeof(IExceptionHandler), new Logging.Log4NetExceptionHandler());

            appBuilder.UseWebApi(config);
        }
    }
}


ApiEndpointsController.cs

using log4net;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Http;

namespace ptest
{
    /// <summary>
    /// URL はすべて [Route("...")] で明示する(規約ルートは使わない)
    /// </summary>
    public class ApiEndpointsController : ApiController
    {
        private static readonly ILog Log = LogManager.GetLogger(typeof(ApiEndpointsController));

        // =========================
        // 共通:メソッド全体 try/catch/finally 相当
        // =========================
        private IHttpActionResult Execute(string actionName, Func<IHttpActionResult> action)
        {
            try
            {
                return action();
            }
            catch (HttpResponseException) // 既に正しくレスポンスとして投げてる例外はそのまま
            {
                throw;
            }
            catch (Exception ex)
            {
                var req = Request;
                var method = req?.Method?.Method ?? "(no-method)";
                var uri = req?.RequestUri?.ToString() ?? "(no-uri)";

                Log.Error($"Unhandled exception in {actionName}: {method} {uri}", ex);

                // 例外時でもプロセスは生かす:500 を返す
                return Content(HttpStatusCode.InternalServerError,
                    new { ok = false, error = "internal server error" });
            }
            finally
            {
                // 必要ならここに「必ず実行したい処理」を書ける
                // Log.Debug($"Finished {actionName}");
            }
        }

        // =========================
        // 1) 最小:疎通確認
        // =========================

        // GET http://localhost:5005/api/v1/ping
        [HttpGet]
        [Route("api/v1/ping")]
        public IHttpActionResult Ping()
        {
            return Execute(nameof(Ping), () =>
            {
                return Ok(new { ok = true, message = "pong", utc = DateTime.UtcNow });
            });
        }

        // =========================
        // 2) 終了:POST で shutdown
        // =========================

        // POST http://localhost:5005/api/v1/shutdown
        // Body は無しでもOK。必要なら JSON を送ってもよい
        [HttpPost]
        [Route("api/v1/shutdown")]
        public IHttpActionResult Shutdown([FromBody] ShutdownRequest body)
        {
            return Execute(nameof(Shutdown), () =>
            {
                // 先にレスポンスを返し、その後で停止要求を出す(クライアントが結果を受け取れるように)
                Task.Run(() =>
                {
                    // 少しだけ待ってから止める(レスポンス送信完了を待つ意図)
                    Thread.Sleep(150);
                    AppLifetime.RequestStop();
                });

                return Ok(new
                {
                    ok = true,
                    message = "shutdown requested",
                    reason = body != null ? body.Reason : null
                });
            });
        }

        // =========================
        // 3) “複雑パターン”代表例(全部明示ルート)
        // =========================

        // (A) 固定 + 複数セグメント
        // GET http://localhost:5005/api/v1/health/ready
        [HttpGet]
        [Route("api/v1/health/ready")]
        public IHttpActionResult Ready()
        {
            return Execute(nameof(Ready), () =>
            {
                return Ok(new { ok = true, status = "ready" });
            });
        }

        // (B) パスパラメータ(文字列)
        // GET http://localhost:5005/api/v1/devices/ABC123/status
        [HttpGet]
        [Route("api/v1/devices/{deviceId}/status")]
        public IHttpActionResult GetDeviceStatus(string deviceId)
        {
            return Execute(nameof(GetDeviceStatus), () =>
            {
                return Ok(new
                {
                    ok = true,
                    deviceId = deviceId,
                    status = "running",
                    utc = DateTime.UtcNow
                });
            });
        }

        // (C) パスパラメータ + ルート制約(int / guid など)
        // GET http://localhost:5005/api/v1/jobs/8f3a0d8c-6ad4-4f20-9d27-2e1b65c8d8f1/items/10
        [HttpGet]
        [Route("api/v1/jobs/{jobId:guid}/items/{itemId:int}")]
        public IHttpActionResult GetJobItem(Guid jobId, int itemId)
        {
            return Execute(nameof(GetJobItem), () =>
            {
                return Ok(new
                {
                    ok = true,
                    jobId = jobId,
                    itemId = itemId
                });
            });
        }

        // (D) パスパラメータ + “コマンド名” のような自由文字列
        // POST http://localhost:5005/api/v1/devices/ABC123/commands/reboot
        // Body: {"args":["now"],"timeoutMs":5000}
        [HttpPost]
        [Route("api/v1/devices/{deviceId}/commands/{commandName}")]
        public IHttpActionResult PostDeviceCommand(string deviceId, string commandName, [FromBody] CommandRequest body)
        {
            return Execute(nameof(PostDeviceCommand), () =>
            {
                var args = body != null && body.Args != null ? body.Args : new string[0];

                return Ok(new
                {
                    ok = true,
                    deviceId = deviceId,
                    command = commandName,
                    args = args,
                    timeoutMs = body != null ? body.TimeoutMs : (int?)null
                });
            });
        }

        // (E) catch-all(残り全部を 1 つのパラメータで受ける)
        // GET http://localhost:5005/api/v1/files/a/b/c.txt
        [HttpGet]
        [Route("api/v1/files/{*path}")]
        public IHttpActionResult GetFilePath(string path)
        {
            return Execute(nameof(GetFilePath), () =>
            {
                return Ok(new
                {
                    ok = true,
                    path = path
                });
            });
        }

        // (F) “固定パス + JSONボディ” (複雑な本体を受ける典型)
        // POST http://localhost:5005/api/v1/batch/execute
        // Body: {"requests":[{"method":"GET","path":"api/v1/ping"},{"method":"POST","path":"api/v1/shutdown"}]}
        [HttpPost]
        [Route("api/v1/batch/execute")]
        public IHttpActionResult BatchExecute([FromBody] BatchExecuteRequest body)
        {
            return Execute(nameof(BatchExecute), () =>
            {
                if (body == null || body.Requests == null)
                {
                    return Content(HttpStatusCode.BadRequest, new { ok = false, error = "body.requests is required" });
                }

                return Ok(new
                {
                    ok = true,
                    count = body.Requests.Count
                });
            });
        }
    }

    // =========================
    // “停止”合図(Program 側が待機して止める想定)
    // =========================
    public static class AppLifetime
    {
        private static readonly CancellationTokenSource _cts = new CancellationTokenSource();

        public static CancellationToken Token
        {
            get { return _cts.Token; }
        }

        public static void RequestStop()
        {
            if (!_cts.IsCancellationRequested)
            {
                _cts.Cancel();
            }
        }
    }

    // =========================
    // DTO
    // =========================
    public class ShutdownRequest
    {
        public string Reason { get; set; }
    }

    public class CommandRequest
    {
        public string[] Args { get; set; }
        public int? TimeoutMs { get; set; }
    }

    public class BatchExecuteRequest
    {
        public List<BatchRequestItem> Requests { get; set; }
    }

    public class BatchRequestItem
    {
        public string Method { get; set; }
        public string Path { get; set; }
    }
}


Logging/Log4NetExceptionLogger.cs

using log4net;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http.ExceptionHandling;

namespace ptest.Logging
{
    public sealed class Log4NetExceptionLogger : ExceptionLogger
    {
        // ★ Log という名前は使わない(override Log(...) と衝突する)
        private static readonly ILog Logger = LogManager.GetLogger(typeof(Log4NetExceptionLogger));

        public override void Log(ExceptionLoggerContext context)
        {
            var req = context?.Request;
            var method = req?.Method?.Method ?? "(no-method)";
            var uri = req?.RequestUri?.ToString() ?? "(no-uri)";

            Logger.Error($"WebApi exception: {method} {uri}", context?.Exception);
        }
    }
}


Logging/Log4NetExceptionHandler.cs

using log4net;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.Http.ExceptionHandling;

namespace ptest.Logging
{
    public sealed class Log4NetExceptionHandler : ExceptionHandler
    {
        private static readonly ILog Logger = LogManager.GetLogger(typeof(Log4NetExceptionHandler));

        public override void Handle(ExceptionHandlerContext context)
        {
            var req = context?.Request;
            var method = req?.Method?.Method ?? "(no-method)";
            var uri = req?.RequestUri?.ToString() ?? "(no-uri)";

            Logger.Error($"WebApi handled exception: {method} {uri}", context?.Exception);

            context.Result = new SimpleErrorResult(req);
        }

        private sealed class SimpleErrorResult : IHttpActionResult
        {
            private readonly HttpRequestMessage _request;

            public SimpleErrorResult(HttpRequestMessage request)
            {
                _request = request;
            }

            public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
            {
                var body = "{\"ok\":false,\"error\":\"internal server error\"}";
                var res = new HttpResponseMessage(HttpStatusCode.InternalServerError)
                {
                    RequestMessage = _request,
                    Content = new StringContent(body, Encoding.UTF8, "application/json")
                };
                return Task.FromResult(res);
            }
        }
    }
}


App.config

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.8" />
    </startup>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-13.0.0.0" newVersion="13.0.0.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
</configuration>

log4net.xml

log4net の RollingFileAppender では datePattern を使って日付付きロール(ファイル分割)ができます。

<?xml version="1.0" encoding="utf-8" ?>
<log4net>
	<!-- 例外ログ:logs\error.log(サイズ+日付でローテーション) -->
	<appender name="ErrorRollingFile" type="log4net.Appender.RollingFileAppender">
		<file value="logs\error.log" />
		<appendToFile value="true" />

		<rollingStyle value="Composite" />
		<datePattern value=".yyyyMMdd" />
		<maximumFileSize value="10MB" />
		<maxSizeRollBackups value="100" />
		<staticLogFileName value="true" />
		<preserveLogFileNameExtension value="true" />
		<countDirection value="1" />

		<layout type="log4net.Layout.PatternLayout">
			<conversionPattern value="%date [%thread] %-5level %logger - %message%newline%exception" />
		</layout>
	</appender>

	<root>
		<level value="INFO" />
		<appender-ref ref="ErrorRollingFile" />
	</root>

</log4net>


packages.config

<?xml version="1.0" encoding="utf-8"?>
<packages>
  <package id="log4net" version="3.2.0" targetFramework="net48" />
  <package id="Microsoft.AspNet.WebApi.Client" version="6.0.0" targetFramework="net48" />
  <package id="Microsoft.AspNet.WebApi.Core" version="5.3.0" targetFramework="net48" />
  <package id="Microsoft.AspNet.WebApi.Owin" version="5.3.0" targetFramework="net48" />
  <package id="Microsoft.AspNet.WebApi.OwinSelfHost" version="5.3.0" targetFramework="net48" />
  <package id="Microsoft.Owin" version="4.2.2" targetFramework="net48" />
  <package id="Microsoft.Owin.Host.HttpListener" version="4.2.2" targetFramework="net48" />
  <package id="Microsoft.Owin.Hosting" version="4.2.2" targetFramework="net48" />
  <package id="Newtonsoft.Json" version="13.0.1" targetFramework="net48" />
  <package id="Newtonsoft.Json.Bson" version="1.0.2" targetFramework="net48" />
  <package id="Owin" version="1.0" targetFramework="net48" />
  <package id="System.Buffers" version="4.5.1" targetFramework="net48" />
  <package id="System.Memory" version="4.5.5" targetFramework="net48" />
  <package id="System.Numerics.Vectors" version="4.5.0" targetFramework="net48" />
  <package id="System.Runtime.CompilerServices.Unsafe" version="4.5.3" targetFramework="net48" />
  <package id="System.Threading.Tasks.Extensions" version="4.5.4" targetFramework="net48" />
</packages>

ptest.csproj

Visual Studio の「Copy to Output Directory」を設定すると、.csproj に <CopyToOutputDirectory> が反映されます。
(.NET Framework プロジェクトでも .csproj は XML です。Visual Studio が裏で編集します。)

<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
  <PropertyGroup>
    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
    <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
    <ProjectGuid>{FAD1C676-174A-491D-B5D9-79D56EB8BEDF}</ProjectGuid>
    <OutputType>WinExe</OutputType>
    <RootNamespace>ptest</RootNamespace>
    <AssemblyName>ptest</AssemblyName>
    <TargetFrameworkVersion>v4.8</TargetFrameworkVersion>
    <FileAlignment>512</FileAlignment>
    <AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
    <Deterministic>true</Deterministic>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
    <PlatformTarget>AnyCPU</PlatformTarget>
    <DebugSymbols>true</DebugSymbols>
    <DebugType>full</DebugType>
    <Optimize>false</Optimize>
    <OutputPath>bin\Debug\</OutputPath>
    <DefineConstants>DEBUG;TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
    <PlatformTarget>AnyCPU</PlatformTarget>
    <DebugType>pdbonly</DebugType>
    <Optimize>true</Optimize>
    <OutputPath>bin\Release\</OutputPath>
    <DefineConstants>TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
  </PropertyGroup>
  <PropertyGroup>
    <StartupObject />
  </PropertyGroup>
  <ItemGroup>
    <Reference Include="log4net, Version=3.2.0.0, Culture=neutral, PublicKeyToken=669e0ddf0bb1aa2a, processorArchitecture=MSIL">
      <HintPath>..\packages\log4net.3.2.0\lib\net462\log4net.dll</HintPath>
    </Reference>
    <Reference Include="Microsoft.Owin, Version=4.2.2.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
      <HintPath>..\packages\Microsoft.Owin.4.2.2\lib\net45\Microsoft.Owin.dll</HintPath>
    </Reference>
    <Reference Include="Microsoft.Owin.Host.HttpListener, Version=4.2.2.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
      <HintPath>..\packages\Microsoft.Owin.Host.HttpListener.4.2.2\lib\net45\Microsoft.Owin.Host.HttpListener.dll</HintPath>
    </Reference>
    <Reference Include="Microsoft.Owin.Hosting, Version=4.2.2.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
      <HintPath>..\packages\Microsoft.Owin.Hosting.4.2.2\lib\net45\Microsoft.Owin.Hosting.dll</HintPath>
    </Reference>
    <Reference Include="Newtonsoft.Json, Version=13.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
      <HintPath>..\packages\Newtonsoft.Json.13.0.1\lib\net45\Newtonsoft.Json.dll</HintPath>
    </Reference>
    <Reference Include="Newtonsoft.Json.Bson, Version=1.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
      <HintPath>..\packages\Newtonsoft.Json.Bson.1.0.2\lib\net45\Newtonsoft.Json.Bson.dll</HintPath>
    </Reference>
    <Reference Include="Owin, Version=1.0.0.0, Culture=neutral, PublicKeyToken=f0ebd12fd5e55cc5, processorArchitecture=MSIL">
      <HintPath>..\packages\Owin.1.0\lib\net40\Owin.dll</HintPath>
    </Reference>
    <Reference Include="System" />
    <Reference Include="System.Buffers, Version=4.0.3.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
      <HintPath>..\packages\System.Buffers.4.5.1\lib\net461\System.Buffers.dll</HintPath>
    </Reference>
    <Reference Include="System.Configuration" />
    <Reference Include="System.Core" />
    <Reference Include="System.Memory, Version=4.0.1.2, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
      <HintPath>..\packages\System.Memory.4.5.5\lib\net461\System.Memory.dll</HintPath>
    </Reference>
    <Reference Include="System.Net.Http.Formatting, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
      <HintPath>..\packages\Microsoft.AspNet.WebApi.Client.6.0.0\lib\net45\System.Net.Http.Formatting.dll</HintPath>
    </Reference>
    <Reference Include="System.Numerics" />
    <Reference Include="System.Numerics.Vectors, Version=4.1.4.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
      <HintPath>..\packages\System.Numerics.Vectors.4.5.0\lib\net46\System.Numerics.Vectors.dll</HintPath>
    </Reference>
    <Reference Include="System.Runtime.CompilerServices.Unsafe, Version=4.0.4.1, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
      <HintPath>..\packages\System.Runtime.CompilerServices.Unsafe.4.5.3\lib\net461\System.Runtime.CompilerServices.Unsafe.dll</HintPath>
    </Reference>
    <Reference Include="System.Threading.Tasks.Extensions, Version=4.2.0.1, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
      <HintPath>..\packages\System.Threading.Tasks.Extensions.4.5.4\lib\net461\System.Threading.Tasks.Extensions.dll</HintPath>
    </Reference>
    <Reference Include="System.Web" />
    <Reference Include="System.Web.Http, Version=5.3.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
      <HintPath>..\packages\Microsoft.AspNet.WebApi.Core.5.3.0\lib\net45\System.Web.Http.dll</HintPath>
    </Reference>
    <Reference Include="System.Web.Http.Owin, Version=5.3.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
      <HintPath>..\packages\Microsoft.AspNet.WebApi.Owin.5.3.0\lib\net45\System.Web.Http.Owin.dll</HintPath>
    </Reference>
    <Reference Include="System.Xml.Linq" />
    <Reference Include="System.Data.DataSetExtensions" />
    <Reference Include="Microsoft.CSharp" />
    <Reference Include="System.Data" />
    <Reference Include="System.Net.Http" />
    <Reference Include="System.Xml" />
  </ItemGroup>
  <ItemGroup>
    <Compile Include="ApiEndpointsController.cs" />
    <Compile Include="Logging\Log4NetExceptionHandler.cs" />
    <Compile Include="Logging\Log4NetExceptionLogger.cs" />
    <Compile Include="Program.cs" />
    <Compile Include="Properties\AssemblyInfo.cs" />
    <Compile Include="Startup.cs" />
  </ItemGroup>
  <ItemGroup>
    <None Include="App.config" />
    <Content Include="log4net.xml">
      <CopyToOutputDirectory>Always</CopyToOutputDirectory>
    </Content>
    <None Include="packages.config" />
  </ItemGroup>
  <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>

Discussion