Access IIS root directory from Asp.net core - asp.net-core

I have shared appsettings in SharedSettings folder.
I am deploying all the asp.net core application in sub directory.
For development, I have created as site with the following directory
c://Website
Here I am keeping my sharedsettings.
But I am developing application from another folder. Here I have configured my application to run as sub application in the web sites.
Folder could be
c://Applications/App1
I want to include the sharedsettings.json in my application. So I have tried the following approach.
.ConfigureAppConfiguration((hostingContext, config) =>
{
var env = hostingContext.HostingEnvironment;
var sharedFolder = Path.Combine(env.ContentRootPath, "..", "Shared");
config
.AddJsonFile(Path.Combine(sharedFolder, "SharedSettings.json"), optional: true) // When running using dotnet run
.AddJsonFile("SharedSettings.json", optional: true) // When app is published
.AddJsonFile("appsettings.json", optional: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);
config.AddEnvironmentVariables();
})
But whenever I have tried to get the hosted url path, It always current application hosted directory. (I understand the reason for the result).
But I don't know how to get the root directory path where it is pointing to the different location.
Reference:
https://andrewlock.net/sharing-appsettings-json-configuration-files-between-projects-in-asp-net-core/

According to your description, the only way to achieve your requirement is using Microsoft.Web.Administration library to select the site root path according to the asp.net core application root path.
Notice: If you want to use Microsoft.Web.Administration, you should make sure your application pool contains enough permission to access the applicationhost.config file.
Normally, we will need localsystem permission. About how to modify application pool permission, you could refer to this article.
Codes:
string path = env.ContentRootPath;
ServerManager mgr = new ServerManager();
//the root path is the parent website's root path
string rootpath = "";
foreach (var site in mgr.Sites)
{
foreach (var application in site.Applications)
{
foreach (var virtualDirectory in application.VirtualDirectories)
{
if (virtualDirectory.PhysicalPath == path)
{
rootpath = site.Applications[0].VirtualDirectories.Where(x=>x.Path=="/").Single().PhysicalPath;
}
}
}
}

Related

IIS ASP.NET 6 startup throws System.IO.DirectoryNotFoundException: D:\agent\_work\38\s\IdentityServer\wwwroot\

We are updating one of our applications, in this case IdentityServer, from .NET 5 to .NET 6. It is being hosted by IIS and deployed by Azure Devops Services. The issue we are seeing is that on our development environment the website fails to load but on our staging environment it runs just fine. The error we are seeing on development is
12:45:37.519|Fatal|1||Host terminated unexpectedly.||
System.IO.DirectoryNotFoundException: D:\agent\_work\38\s\IdentityServer\wwwroot\
at Microsoft.Extensions.FileProviders.PhysicalFileProvider..ctor(String root, ExclusionFilters filters)
at Microsoft.Extensions.FileProviders.PhysicalFileProvider..ctor(String root)
at Microsoft.AspNetCore.Hosting.StaticWebAssets.StaticWebAssetsLoader.<>c.<UseStaticWebAssetsCore>b__1_0(String contentRoot)
at Microsoft.AspNetCore.StaticWebAssets.ManifestStaticWebAssetFileProvider..ctor(StaticWebAssetManifest manifest, Func`2 fileProviderFactory)
at Microsoft.AspNetCore.Hosting.StaticWebAssets.StaticWebAssetsLoader.UseStaticWebAssetsCore(IWebHostEnvironment environment, Stream manifest)
at Microsoft.AspNetCore.Hosting.StaticWebAssets.StaticWebAssetsLoader.UseStaticWebAssets(IWebHostEnvironment environment, IConfiguration configuration)
at Microsoft.AspNetCore.WebHost.<>c.<ConfigureWebDefaults>b__9_0(WebHostBuilderContext ctx, IConfigurationBuilder cb)
at Microsoft.AspNetCore.Hosting.GenericWebHostBuilder.<>c__DisplayClass9_0.<ConfigureAppConfiguration>b__0(HostBuilderContext context, IConfigurationBuilder builder)
at Microsoft.Extensions.Hosting.HostBuilder.BuildAppConfiguration()
at Microsoft.Extensions.Hosting.HostBuilder.Build()
at IdentityServer.Program.Main(String[] args) in D:\agent\_work\38\s\IdentityServer\Program.cs:line 23
The path it reports, D:\agent\_work\38\s\IdentityServer\wwwroot\ is interesting because that path is the same as the path from the DevOps build machine. We don't see this error if we revert back to .NET 5 and we don't see the problem on our staging machine.
The Program.cs class is defined as
using System;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using NewRelic.LogEnrichers.Serilog;
using Serilog;
using Serilog.Events;
namespace IdentityServer
{
public class Program
{
public static int Main(string[] args)
{
try
{
CreateLogger();
Log.Information("Starting host...");
CreateHostBuilder(args).Build().Run();
return 0;
}
catch (Exception ex)
{
Log.Fatal(ex, "Host terminated unexpectedly.");
return 1;
}
finally
{
Log.CloseAndFlush();
}
}
public static void CreateLogger()
{
var configuration = GetConfiguration();
Log.Logger = new LoggerConfiguration()
.ReadFrom.Configuration(configuration)
.Enrich.FromLogContext() // allows logging middleware to inject output values
.Enrich.WithThreadId()
.Enrich.WithNewRelicLogsInContext()
.CreateLogger();
}
public static IHostBuilder CreateHostBuilder(string[] args)
{
var configuration = GetConfiguration();
return Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(
webBuilder =>
{
webBuilder.UseConfiguration(configuration);
webBuilder.UseSerilog();
webBuilder.UseIIS();
webBuilder.CaptureStartupErrors(true);
webBuilder.UseStartup<Startup>();
});
}
private static IConfiguration GetConfiguration()
{
var environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
var builder = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.AddJsonFile($"appsettings.{environment}.json", true, true);
var configuration = builder.Build();
return configuration;
}
}
}
We do have other .NET 6 web applications running just fine on this instance of IIS. I was thinking that the problem might be in our release pipelines but they are identical in their task configurations between the environments. Tried looking for the directory path in the code or configuration but don't see it anywhere. Have tried manually setting the WebRoot and ContentRoot paths via .UseWebRoot("path to folder") and .UseContentRoot("path to folder") in the Program.cs but didn't see any change in the logs or the app starting.
Even updated the web.config file to have the exact path for executing the project dll in the aspNetCore element but still no change.
Update 10 Feb 2022
Added debug output to the startup to verify file and folder paths. Everything in the environment variables and execution file path look correct.
ASPNETCORE_IIS_PHYSICAL_PATH - C:\inetpub\webapps\IdentityServer\
Executable Path: C:\inetpub\webapps\IdentityServer\IdentityServer.dll
The problem ended up being how we were pushing our updates out to the servers from DevOps. Our pipelines were built to copy over files out of the Release directory of the build folder. One of the problems with this approach is that files not needed for a site to run but generated during a build are also copied to the release server. In this case, a new file which is generated in .NET 6, .staticwebassets.runtime.json, was getting copied to our servers.
The way .NET 6 seems to behave is that if the environment is set to Development then it will look for this file to figure out where the static web assets are located. If the file doesn't exist then it will assume the files are in a wwwroot sub-directory of the site. This makes sense for instances where you are running the project from your local Visual Studio. More details about this file are available in another SO post with links to the source code in GitHub. To fix our problem we changed our release pipeline to use the publish.zip file that is generated when you run the publish command on a solution. The archive only contains the files needed to run the site, so none of the extraneous files like .staticwebassets.runtime.json are included. We should have been doing this the whole time... lesson learned.
We now unzip the publish.zip file, apply any file transformations, then copy the unzipped files to the web server.

Using virtual directory with ASP.NET Core 3.1

In ASP.NET framework 4.8 and below version the web application use IIS for processing and show data. And when we need to work with other resource like folders and network resource we can easily create Virtual Directory in IIS and map to physical path and my application work theme like normal folder.
but in Net Core we use Kestrel and IIS work as a proxy and Virtual Directory not recognized by Kestrel. I use this code but not work in function. Write this section in Configure Function
app.UseFileServer(new FileServerOptions
{
FileProvider = new PhysicalFileProvider(#"E:\\MyFiles"),
RequestPath = new PathString("/PFiles"),
EnableDirectoryBrowsing = true
});
and this is my code :
var folder = Path.Combine(environment.WebRootPath, "temp");
var fileName = Path.Combine(environment.WebRootPath, "temp\\test.jpeg");
var basePath = Path.Combine(environment.WebRootPath, "PFiles");
var yearPath = Path.Combine(basePath, "2020");
var monthpath = Path.Combine(basePath, "2020", "06");
if (!Directory.Exists(yearPath))
{
Directory.CreateDirectory(yearPath);
}
if (!Directory.Exists(monthpath))
{
Directory.CreateDirectory(monthpath);
}
var dpath = Path.Combine(basePath, "2020", "06");
var destinationPath = Path.Combine(environment.WebRootPath, dpath);
System.IO.File.Move(fileName, destinationPath);
but I receive Access denied Error or create directory inside of wwwroot folder. So, what must I do?
you get this error because iis default account does not have enough permission to access the folder.
you could try to assign the iis_iusrs , iusr, or IIS AppPool<myappoolname> permission to the folder where you want to create directory.

Force the usage of a bin folder

I have a larger ASP.NET Core project which means that a lot of DLLs are included in the publish.
Since all of the DLLs are placed in the root folder it's cumbersome to navigate the folder structure (to mange configs etc) due to the sheer amount of files.
Is it possible to tell ASP.NET Core that it should load all assemblies from another folder (bin\)?
I would do it in opposite side. If your problem is just config files then relocate them into config folder and keep them there. As of now dotnet will publish your project + framework (if you use self contained flag).
You can configure aspnetcore to use files
config.AddJsonFile("config/appsettings.json", optional: false, reloadOnChange: false);
So then that folder will be on top and better accessible
Yes in root folder there still be web.config but in my project that file usually is same for all environments. But again it depends where you deploy, because if you deploy to non IIS environment then you don't even need it
Hi How about the Managed Extensibility Framework , It allows you load assemblies dynamically.
Use BuildManager to load assemblies dynamically,
string pluginPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "plugins");
foreach (string f in Directory.GetDirectories(pluginPath))
{
string binPath = Path.Combine(f, "bin");
if (Directory.Exists(binPath))
{
foreach (String file in Directory.GetFiles(binPath, "*.dll"))
{
Assembly a = Assembly.LoadFrom(file);
BuildManager.AddReferencedAssembly(a);
}
}
Resolve assemblies using below code,
protected virtual void Application_Start(object sender, EventArgs e)
{
//...
AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;
}
System.Reflection.Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
{
var currentAssemblies = AppDomain.CurrentDomain.GetAssemblies();
foreach (var assembly in currentAssemblies)
{
if (assembly.FullName == args.Name || assembly.GetName().Name == args.Name)
{
return assembly;
}
}
return null;
}

.Net Core web api needs to consume web service from configuration file

In my .Net Core application I am consuming Web Service using
Add -> Connected services -> WCF Service Preview(nuget package) and added the web service and used the service methods.
However, now clients moved the Web Service to internal Web Servers and I do not have access to the service from my development environment. So I am not able to access the service methods and build my solution and publish.
Is there any way I can pass the Service URL from Configuration file?
Example:
For Dev Environment - http://dev.svc
For Prod Environment - http://prod.svc
Yes, you can. I suggest you to read whole article about the configuration in ASP.NET Core, as there are lots of things you may find useful. In general, you can get the config files for each of environments with code like this:
public class Startup
{
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
// note that here we do override the values by specific file for an emvironment
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
// and this line will get the environment variables from server machine
.AddEnvironmentVariables();
Configuration = builder.Build();
}
}
JSON files could be something like this:
appsettings.json
{
"serviceUrl": "",
}
appsettings.Development.json
{
"serviceUrl": "http://dev.svc",
}
appsettings.Production.json
{
"serviceUrl": "http://prod.svc",
}
Also you may find useful the Working with multiple environments article.

How do we set ContentRootPath and WebRootPath?

We're ending up with the following ContentRoot and WebRoot when we run our app from IIS.
ContentRoot: C:\MyApp\wwwroot
WebRoot: C:\MyApp\wwwroot\wwwroot
Here is how we are setting ContentRoot and WebRoot.
public class Startup
{
private readonly IHostingEnvironment _hostingEnv;
public Startup(IHostingEnvironment hostingEnv)
{
_hostingEnv = hostingEnv;
}
public void Configure(IApplicationBuilder app)
{
app.Run(context =>
{
// test output
context.Response.WriteAsync(_hostingEnv.ContentRootPath + "\r\n");
return context.Response.WriteAsync(_hostingEnv.WebRootPath + "\r\n");
});
}
public static void Main(string[] args)
{
var contentRoot = Directory.GetCurrentDirectory();
var webRoot = Path.Combine(contentRoot, "wwwroot");
var host = new WebHostBuilder()
.UseKestrel()
.UseIISPlatformHandlerUrl()
.UseContentRoot(contentRoot) // set content root
.UseWebRoot(webRoot) // set web root
.UseStartup<Startup>()
.Build();
host.Run();
}
}
From intellisense I see that...
ContentRootPath contains the application content files.
WebRootPath contains the web-servable content files.
How do we make the test output look instead like this:
ContentRoot: C:\MyApp\
WebRoot: C:\MyApp\wwwroot\
While RC2 documentation is still being prepared, here is what I learned while trying to deploy pre-RC2 app as Azure Web App:
There is no Visual Studio tooling yet, so the app must be published and deployed manually over FTP. For publishing, use: dotnet publish --configuration Release --output ./approot
If connected to Azure over FTP, you will probably see something similar to:
The "approot" folder can be replaced with the published one (the web.config is left in the approot).
The "approot" must be configured as a virtual application in Azure Portal (the default was site\wwwroot):
An the last thing to get static files served from the wwwroot folder, the Startup.cs file should be modified to include custom UseWebRoot call:
var currentDirectory = Directory.GetCurrentDirectory();
var host = new WebHostBuilder()
.UseKestrel()
.UseWebRoot(Path.Combine(currentDirectory, "..", "wwwroot"))
.UseDefaultHostingConfiguration(args)
.UseIISIntegration()
.UseStartup<Startup>()
.Build();
After these steps you should have ASPNET Core pre-RC2 web app running on Azure.
In RC2, if we put the web.config beside wwwroot and point IIS at the MyApp directory like this...
MyApp
web.config
wwwroot
...the code from the original question outputs this...
ContentRoot: C:\MyApp\
WebRoot: C:\MyApp\wwwroot\