I know that is located in HttpContext.Request.PathBase
, however I need it to configure my cookie before I have any HttpContext
(in Startup.cs
).
My problem:
When devops configure application they have to set path twice. Once in IIS application (so hosting knows what should be served) and in my appsettings.json (so application knows where to set cookies - multiple instances can work on server). I would like to configure it once in IIS, and have config passed to my application.
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).