LoginSignup
1

More than 5 years have passed since last update.

Asp.Net Coreでコマンドライン引数で起動するURLを設定する

Posted at

Asp.Net Coreでコマンドライン引数で起動するURLを設定する

LinuxでもC#でサーバーを立てられる!

なんと言ってもLinuxでC#のWebサーバーですよ。
かなり遜色ない感じで動いてくれるので感動です。

起動するURLの指定方法は

ところが、dotnet runコマンドで起動すると、\Properties\launchSettings.json の設定に従って起動するURLが指定されたりします。
まあ、これでもnginxをフロントにしたりすればあまり問題もないのですが。
dockerのコンテナ内で起動しようとしたときに大問題になってしまうのです。

そういう時にはコマンドライン引数で起動URLを指定できる方が利便性が増します。
というわけで、実コード。

コード

通常、Visual Studio(軟弱でゴメン…)で空のAsp.Net Coreのプロジェクト作ったら以下のようになります。

Program.cs
public static void Main(string[] args)
{
    var host = new WebHostBuilder()
        .UseKestrel()
        .UseContentRoot(Directory.GetCurrentDirectory())
        .UseIISIntegration()
        .UseStartup<Startup>()
        .Build();

    host.Run();
}

起動するURLを指定するには .UseUrls() を使用します。
こんな感じになりますね。

Program.cs
    var host = new WebHostBuilder()
        .UseUrls("http://localhost:6001")
        .UseKestrel()
        .UseContentRoot(Directory.GetCurrentDirectory())
        .UseIISIntegration()
        .UseStartup<Startup>()
        .Build();

そして、 neueccさんのこの記事 と組み合わせて…。

Program.cs
public static void Main(string[] args)
{
    var options = new HashSet<string> { "-u" };
    string key = null;
    var opt_args = args
        .GroupBy(s => options.Contains(s) ? key = s : key)
        .ToDictionary(g => g.Key, g => g.Skip(1).FirstOrDefault());

    IWebHostBuilder host_builder = new WebHostBuilder();
    if (opt_args.Keys.Contains("-u"))
    {
        host_builder = host_builder.UseUrls(opt_args["-u"]);
    }

    var host = host_builder
        .UseKestrel()
        .UseContentRoot(Directory.GetCurrentDirectory())
        .UseIISIntegration()
        .UseStartup<Startup>()
        .Build();

    host.Run();
}

こんな感じになりました!
これで、dockerコンテナ内で

#!/bin/sh

HOSTNAME=`hostname`
dotnet restore
dotnet run --configuration Release -u http://$HOSTNAME:5000/ > site.log

こんなスクリプトで起動をかけられます。

なんでdockerにこだわるの?

や、仕事で与えられたサーバーがCentOS6だったのですよ…。

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1