Starting in .NET 8, you can get this information from the public IIISEnvironmentFeature available on the IIS IServer implementation.
// Obtain the IServer implementation from the service provider.
// Can be obtained from HttpContext, dependency injection, etc.
IServer server = context.RequestServices.GetService<IServer>();
// Ask for the IIISEnvironmentFeature.
var iisEnv = server.Features.Get<IIISEnvironmentFeature>();
if (iisEnv != null)
{
string appVirtualPath = iisEnv.ApplicationVirtualPath;
// Other IIS properties can be accessed from this interface too.
}
The IIISEnvironmentFeature was introduced in .NET 8, but note that it can be null if the version of your installed ASP.NET Core IIS Module is significantly out of date.
Also note that ApplicationVirtualPath seems to always be uppercase, which could catch some migrating .NET Framework code by surprise. The only way I've found to get a correctly cased application virtual path is to extract it from the ApplicationId (another property on IISEnvironmentFeature).