Get application virtual base path in aspnet core

You can check the environment variable ASPNETCORE_APPL_PATH. This is the variable AspNetCoreModule provides so that PathBase can be set correctly. See https://github.com/aspnet/IISIntegration/blob/df88e322cc5e52db3dbce4060d5bc7db88edb8e4/src/Microsoft.AspNetCore.Server.IISIntegration/WebHostBuilderIISExtensions.cs#L19


There is a little confustion here that should be clarified.

You want to know application virtual path at application startup. However application virtual path is a concept of the hosting and specific request rather than underlying application. Hosting service uses this virtual path to map incoming url to application root. In IIS you can map multiple virtual paths to the same physical directory, e.g. /myApp1 and /myApp2 will point to the same application. Which of these paths do you want to get at application startup?

That's actually the reason why IHostingEnvironment interface does not provide any property for getting application virtual path. Another thing when application processes the request. In this case specific URL is requested and ASP.NET could provide requested virtual path in HttpContext.Request.PathBase.

You should reconsider your use case and check whether you actually need application virtual path for cookie configuration. It could be the XY problem. If you still have doubts regarding cookie configuration, please formulate it as a new question with specific details for your scenario.