Skip to content

MS_GettingWebSitePaths

nishi_74322014 edited this page Aug 21, 2026 · 1 revision

Webサイトのパスを取得する方法

概要

Web サイトの様々なパスを取得する方法。

補足(「物理パス」と「仮想パス」の区別): Web では
2 種類のパスが常に併存するため、まずこの区別を押さえる。

ブラウザから見える URL                 → 仮想パス
  https://example.com/app/Order/List
                      ~~~~~~~~~~~~~~~
                      /app/Order/List

サーバ上の実際の場所                   → 物理パス
  C:\inetpub\wwwroot\app\Order\List.aspx
仮想パス 物理パス
/app/Order/List C:\inetpub\...\List.aspx
用途 リンク・リダイレクトの生成 ファイルの読み書き
変換 Server.MapPath()(仮想 → 物理)

仮想ディレクトリ配下に配置されるか(/app/)どうか
仮想パスが変わるため、URL をハード コーディングしないことが
本ページの実務上の主旨である。

物理ファイル パス

HttpServerUtility.MapPath

仮想パスに対応する物理ファイル パス

Page 内

Server 組み込みオブジェクトから HttpServerUtility インスタンスを取得。

string path = Server.MapPath("./");

Page 外

HttpContext.Current.Server プロパティから HttpServerUtility インスタンスを取得。

string path = HttpContext.Current.Server.MapPath("./");

補足(HttpContext.Current は避ける): 「Page 外」から
HttpContext.Current を使う方法は動作するが、
設計としては望ましくない

・静的プロパティに依存するため、単体テストできない
・[async/await](MS_AsyncAwait) の後で null になることがある
  (ASP.NET の同期コンテキストに依存するため)
・バッチや別スレッドから呼ぶと null

業務ロジックの層にパスの解決を持ち込まない
(必要なパスは引数で渡す)のが定石である。

ASP.NET Core では HttpContext.Current 自体が存在しない
必要なら IHttpContextAccessor を注入する
ASP.NET Core における DI)が、
パスの取得には後述の IWebHostEnvironment を使うのが正しい。

HttpRequest

PhysicalApplicationPath

https://learn.microsoft.com/en-us/dotnet/api/system.web.httprequest.physicalapplicationpath

サーバー アプリケーションのルート ディレクトリの物理ファイル システム パス

PhysicalPath

https://learn.microsoft.com/en-us/dotnet/api/system.web.httprequest.physicalpath

要求された URL に一致する物理ファイル システム パス

仮想パス

HttpRequest

ApplicationPath

https://learn.microsoft.com/en-us/dotnet/api/system.web.httprequest.applicationpath

現在のアプリケーションのルート仮想パス(「/」や「/アプリ名」のような)。

CurrentExecutionFilePath

https://learn.microsoft.com/en-us/dotnet/api/system.web.httprequest.currentexecutionfilepath

現在の要求の仮想パス(Transfer または Execute を反映)

FilePath

https://learn.microsoft.com/en-us/dotnet/api/system.web.httprequest.filepath

現在の要求の仮想パス(Transfer または Execute を反映しない)

Path

https://learn.microsoft.com/en-us/dotnet/api/system.web.httprequest.path

現在の要求の仮想パス(URL 拡張子付きリソースに追加パス情報を反映)

補足(具体例で見る違い): 4 つの違いは文章だと分かりにくいので、
実際の値を並べておく。

前提: アプリを仮想ディレクトリ /app に配置し、
      /app/Default.aspx で Server.Transfer("Other.aspx") した後、
      URL は /app/Default.aspx/extra

  ApplicationPath            → /app
  FilePath                   → /app/Default.aspx       (Transfer 前)
  CurrentExecutionFilePath   → /app/Other.aspx         (Transfer 後)
  Path                       → /app/Default.aspx/extra (PathInfo 付き)
  PathInfo                   → /extra

ApplicationPath が最も使用頻度が高い
「アプリがルートに置かれるか、仮想ディレクトリ配下に置かれるか」を
吸収するために使う。

// ✗ ルート配置を前提にしている
Response.Redirect("/Order/List");

// ○ アプリのルートからの相対("~/" が ApplicationPath に解決される)
Response.Redirect("~/Order/List");
string url = VirtualPathUtility.ToAbsolute("~/Order/List");

~/ 記法を使えば、ApplicationPath を意識せずに済む。
ASP.NET MVC では Url.Content("~/...") /
Url.Action(...) を使う(ASP.NET MVCの用語)。

補足(ASP.NET Core での対応物/最新化): System.Web が無いため、
API がすべて置き換わっている

ASP.NET (System.Web) ASP.NET Core
Server.MapPath("~/x") Path.Combine(env.ContentRootPath, "x")
Server.MapPath("~/wwwroot/x") Path.Combine(env.WebRootPath, "x")
Request.PhysicalApplicationPath env.ContentRootPath
Request.ApplicationPath Request.PathBase
Request.FilePath / Path Request.Path
Request.Url Request.GetDisplayUrl()(拡張メソッド)
public class MyService(IWebHostEnvironment env)
{
    public string GetTemplatePath()
        => Path.Combine(env.ContentRootPath, "Templates", "invoice.html");

    public string GetImagePath()
        => Path.Combine(env.WebRootPath, "images", "logo.png");
}

ContentRootPathWebRootPath の区別が重要である。

ContentRootPath  … アプリのルート(appsettings.json などがある場所)
WebRootPath      … wwwroot(静的ファイルとして公開される場所)
                    ← ここに置いたものは URL で直接取得できる

機密ファイルを wwwroot に置かないこと。
ASP.NET では「公開したくないものを塞ぐ」設計だったのに対し、
ASP.NET Core は**「公開するものだけを wwwroot に置く」**という
逆の設計になっている(ASP.NET MVCの用語 のフォルダ構成も参照)。

PathBase は、リバース プロキシ配下で
サブパスに配置する場合(/app の下に置く)に効いてくる
ASP.NET CoreのWebサーバ
UseForwardedHeaders と併せて設定する)。

app.UsePathBase("/app");

参考

Microsoft Learn


Tags: 移行, .NET開発, ASP.NET

NetDevInfraWiki

マイクロソフト系技術情報 Wiki
Open 棟梁 Wiki

(未着手)

開発基盤部会 Wiki

移行管理: DONETODO

Clone this wiki locally