LoginSignup
4
10

More than 5 years have passed since last update.

ASP.NET Core MVC における Server.MapPath によるコンテンツ ルート パスの取得

Last updated at Posted at 2017-04-10

ASP.NET 時代には、随分とお世話になった "Server.MapPath()" メソッド
コンテンツ ルート下に配置したリソース ファイルを取得する際に多用したと思います。

しかしながら、ASP.NET Core では、"Server.MapPath()" を利用することができません。

ASP.NET Core では、コンテンツ ルートのパスを取得するには、Web ホストの情報を提供する Microsoft.AspNetCore.Hosting.IHostingEnvironment のインスタンスの "ContentRootPath" プロパティから取得します。

IHostingEnvironment のインスタンスは、各 MVC のコントローラーのコンストラクターの引数経由で取得します。

[.NET Core 環境におけるオブジェクトとファイルの JSON シリアライズ、JSON 逆シリアライズ]
http://qiita.com/hiromasa-masuda/items/d63bbc042f6b81ee08a5

上記の投稿で説明した JSON 逆シリアライズを組み合わせたサンプル コードを以下に掲載しています。

HomeController.cs

public class HomeController : Controller
{
        /// <summary>
        /// IHostingEnvironment のインスタンスを保持
        /// </summary>
        private Microsoft.AspNetCore.Hosting.IHostingEnvironment _hostingEnvironment = null;

        /// <summary>
        /// コンストラクター経由で、IHostingEnvironment のインスタンスを取得
        /// </summary>
        /// <param name="hostingEnvironment"></param>
        public HomeController(Microsoft.AspNetCore.Hosting.IHostingEnvironment hostingEnvironment)
        {
            //IHostingEnvironment をフィールドに保持
            this._hostingEnvironment = hostingEnvironment;
        }

        public IActionResult Index()
        {
            //シリアライザーのインスタンスを生成
            DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(Person));

            string filePath = Path.Combine(this._hostingEnvironment.ContentRootPath, "Files", "person.json");

            Person deSerializedPerson = null;

            //入力ファイル ストリームの生成
            //using (FileStream stream = new FileStream(filePath, FileMode.Open))
            using (Stream stream = System.IO.File.Open(filePath, FileMode.Open))
            {
                //逆シリアライズ
                deSerializedPerson = jsonSerializer.ReadObject(stream) as Person;
            }

            return View(deSerializedPerson);
        }
}

ルート以下の Files フォルダに格納された person.json ファイルをロードし、Person オブジェクトを逆シリアライズにより生成。
この JSON シリアライズ ファイルをロード時に、IHostingEnvironment.ContentRootPath を利用。

個人的には、突如としてコード上にあらわれる Server オブジェクトを利用するより、このように、各コントローラーのコンストラクターにより情報を受け渡す方が、可読性が高くて良いと考えています。

4
10
0

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
4
10