Search code examples
asp.net-corepathrequest

ASP.NET Core 6 MVC on IIS - path issues


I have an ASP.NET Core 6 MVC web app that I am running on IIS. There is a virtual application in IIS under which the app is deployed.

However despite everything I have tried, I cannot get a path with the virtual application name included in order to include in the asp-route-returnurl.

So the URL looks something like this

http://servername/virtualappname/asp-net-app-url

I tried using context.request.path, host, pathbase, etc. But nothing brings back the virtualappname. I am sure I can get it in javascript with location.href. But how do I fetch that full url in ASP.NET Core. Path and Path base only seem to get me from /asp-net-app-url onwards.

I can hardcode it. But wanted to avoid if not necessary.

Thanks in advance


Solution

  • First of all, we need to know that asp.net core belongs to the application level, and is finally deployed under the main application site, and it cannot directly obtain the path of the child application in the machine level.

    If we want to do this, we need to do it with PowerShell or ServerManager class.

    1.Query the subsite name by Powershell.

    enter image description here

    2.Query via code by using ServerManager class

    using Microsoft.Web.Administration;
    
    public IActionResult Test1()
    {
        var paths = new List<string>();
        try
        {
            using (var serverManager = new ServerManager())
            {
                Site site = serverManager.Sites["test"];
                if (site != null)
                {
                    foreach (Application app in site.Applications)
                    {
                        if (app.Path != "/") // Ignore the root application
                        {
                            paths.Add(app.Path);
                        }
                    }
                }
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine("Error: " + ex.Message);
        }
        return Ok(paths);
    }
    

    Test Result

    enter image description here