Accessing a web.config file in a third party libra

2019-05-18 10:53发布

问题:

I'm writing an IHttpFilter which needs to be in a seperate project (these are all C# projects) to be used in a set of ASP.NET MVC Applications. In the IHttpFilter I have to determine a few things that are specified in the web.config file.

Is there a way of retrieving the current web.config file from an external assembly at runtime? There are three settings that I need to obtain (strings).

The other problem is that I need to reference a bunch of files (images) but I'm not sure whether to place it in the ASp.NET MVC Application or in the IHttpHandler project.

回答1:

From external assembly I understand that you mean an assembly generated by another project referenced by the web application.

At runtime, your web application will retrieve its entire configuration included those retrieved by referenced assemblies - from the web application's web.config. You don’t have to change anything in you IHttpHandler code.

So while at design-time you should probably have those settings on each project’s config files, during run-time, all of the referenced projects config files should be merged into the web application’s web.config file.

About the images: On the small test I’ve done here, I’ve put images on a referenced project setting them as content and to copy always to output directory. While the assembly got copied to the web application’s bin folder as I expected, the images were not copied to anywhere besides their own projects output directory.

So for the sake of simplicity, I would put the images at an appropriate folder in the web applications project.



回答2:

Here is some code I recently wrote to open a web.config file from another process:

var configFile = new FileInfo(configPath);

WebConfigurationFileMap map = new WebConfigurationFileMap();

var appBase = 
    new VirtualDirectoryMapping(configFile.DirectoryName, true, configFile.Name);
map.VirtualDirectories.Add("/", appBase);

return WebConfigurationManager.OpenMappedWebConfiguration(map, "/");

The configPath parameter is simply a string that contains the path to the web.config.