web.config in subdirectory in mvc 4 - asp.net

This question seems to have been asked quite a bit but none actually solve the problem for me. I have an ASP.NET MVC4 application with an area. Inside this area I have a web.config with overridden appsettings. These settings don't seem to be picked up when attempting to read them in a controller within the area.
-MyApp
-Areas
-MyArea
-Controllers
-MyController
-Web.config
-Web.config
In MyApp\Web.config I have:
<appSettings>
<add key="DefaultDisplayMode" value="Configuration" />
</appSettings>
In MyApp\Areas\MyArea\Web.config I have:
<appSettings>
<add key="DefaultDisplayMode" value="Review" />
<add key="SubSetting" value="Testing" />
</appSettings>
In MyController if I query the app settings, I see:
DefaultDisplayMode: Configuration
I expect to see:
DefaultDisplayMode: Review
SubSetting: Testing
I've tried with both:
System.Configuration.ConfigurationManager.AppSettings["..."]
System.Web.Configuration.WebConfigurationManager.AppSettings["..."]
I even tried with the following (over the top) structure with no luck:
-MyApp
-Areas
-MyArea
-Controllers
-MyController
-Web.config
-Web.config
-Web.config
Does anybody know why my subdirectory appSettings aren't working?

IIS will load the web.config based on the URL, not based on the code that your routed request executes.
You can create an empty folder structure that mimics the required route and add the config file there. If that does not work, you can use <location> tag in the main configuration file - but the path in the location tag also has to match the URL and not the code.

Related

Api is giving 404 when added + as part of URL (%2B)

I am using asp.net core 3.1 and receiving values from URL. Its working fine but when I add "+" sign as a part of URL, it gives 404.
Example : localhost:9000/api/get/%2B12/values
+ is a special character. It should ideally be should be URL encoded as %2B.
Turns out it's not really required though (like in the screenshot below) but I still recommend it. (See: URL encoding the space character: + or %20?)
Here's a working example controller:
[ApiController]
public class ExpController : Controller
{
[Route("/api/exp/{arg}/values")]
public IActionResult Test(int arg) =>
Ok($"The arg is: {arg}");
}
Note how the route parameter is a int. For more complex values (other than just 12, +12, -12; eg: 12+12) the route will need to be a string instead.
version above IIS7 will refuse to request the URL contains symbols such as '+' by default. The following modifications are required. You need add the following nodes in web.config:
<system.webServer>
<security>
<requestFiltering allowDoubleEscaping="true"/>
</security>
</system.webServer>
But now the .net core project does not have web.config to configure IIS options. You need to go to the location:
vs project location /.vs/config/applicationhost.config to add the above node.
Note that the .vs folder is a hidden folder and needs to be set visible.
Option 1 :
Mess with config to bypass request validation / allowDoubleEscaping (Asp.Net)
You need to be aware for certain risk/vulnabilirities described here:
https://stackoverflow.com/a/53621095/4798459
.netcore :
Since this issues is related to IIS, not your solution. You need to handle a web.config
Create a new web.config on the root of your project.
Right click, properties, set "Copy to Output Directory" to "Copy Always"
When you publish a .net core app, a "basic web.config" file is created. (For iis)
You need to copy the content of the "basic web.config".
You can find the auto-generated web.config file:
Where your app is already published (local server?)
You can also publish your api temporarly to a random path on your PC, see details here https://docs.devexpress.com/OfficeFileAPI/401445/dotnet-core-support/publish-net-core-application)
The web.config should like so, i added the tag with a a commentt
<configuration>
<location path="." inheritInChildApplications="false">
<system.webServer>
<!-- XML node <security> is added to allow allowDoubleEscaping and add support for + paremeter in a route. Risk:https://stackoverflow.com/a/53621095/4798459 -->
<security>
<requestFiltering allowDoubleEscaping="true"></requestFiltering>
</security>
<handlers>
<add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModuleV2" resourceType="Unspecified" />
</handlers>
<aspNetCore processPath="dotnet" arguments="[.\SolutionName.Namespace.dll]" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" hostingModel="inprocess" />
</system.webServer>
</location>
</configuration>
Make sure that the step 2 is done before publishing your app otherwise it wont work.
Not tested with iisexpress
Option 2
Change pramater type in the api. Intead of being on the route, use a queryString instead
Option 3
Custom solution for request filtetring /routing, which i don't have any example, and seems a bit "over the top".
Option 4, to avoid:
Use an other solution for encoding / decoding special caracter (I have not tried)
https://stackoverflow.com/a/55637235/4798459

IIS error 500.19 error when reading web.config

I am running IIS under Windows Server 2016 and I'm trying to run an ASP.Net core 3.1 application but I can't get past this error:
500.19 error
(The language in the picture is Hungarian, but it contains no useful information whatsoever, just an example)
Here is my web.config
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<location path="." inheritInChildApplications="false">
<system.webServer>
<handlers>
<add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModuleV2" resourceType="Unspecified" />
</handlers>
<aspNetCore processPath=".\Minibizz.Routing.Web.exe" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" hostingModel="inprocess" />
</system.webServer>
</location>
</configuration>
What am I missing?
P.S.: The web.config was created by Visual Studio 2019.
The reason behind the issue:
That error message goes on to say what exactly is bad about your configuration file, hence you should refer the “Config Error” and “Config Source” sections. This problem occurs because of the ApplicationHost.config file or the Web.config file contains a malformed or unsupported XML element.
if you are using url rewrite rule then install url rewrite Extention of iis. Enable ANCM logging, ie. set stdoutLogEnabled="true" stdoutLogFile=".\logs\stdout\" (I think the path needs to end by a backslash), then run the web app and see if something gets logged into the stdout folder. Verify that the log directory exists at the path referenced by the web config. If it does not, create it. The path shown in your config would place the "logs" directory in the root folder of the deployed site. Verify that the application pool has to write access to the logs directory.
Make sure you installed the .net bundle.check that you installed below iis feature:
You may also need to verify that the path to the dotnet executable exists in the deployment machine's environment variables. To check this, first find the path where dotnet.exe is installed. It is generally located in either C:\Program Files\dotnet or C:\Program Files (x86)\dotnet. Once you know the path, ensure that the path exists in your Environment Variables.
The web.config content seems to be correct. If you use a clean web.config copy, does the problem persist? If the issue can be solved by replacing web.config with clean configuration content, then the problem is exactly with this web.config. In this case, I suggest you remove parts of the web.config content to narrow down the issue. If the pages show correctly after you remove one section, then the problem is with that section. You need double-check what's wrong with the section and update the correct configuration.
If the problem remains even with clean web.config content, I suggest you access other pages in different folders in your site to see if the problem still exists.
you could refer this below link for how to publish asp.net core site in iis:
https://learn.microsoft.com/en-us/aspnet/core/tutorials/publish-to-iis?view=aspnetcore-3.1&tabs=visual-studio

Connection string in parent folder of WCF project is throwing error as The configSource '..\connectionStrings.config' is invalid

We have multiple WCF projects and we want place the all connection strings in one connectionStrings.config file and use it from there. For this I have tried the following:
connectionStrings.config file in parent folder of all WCF projects (path: D:\Projects\connectionStrings.config)
<connectionStrings>
<add name="Name"
providerName="System.Data.ProviderName"
connectionString="Valid Connection String;" />
</connectionStrings>
web.config file of each WCF Project (path: D:\Projects\SampleWCFProject\web.config)
<?xml version='1.0' encoding='utf-8'?>
<configuration>
<connectionStrings configSource="..\connectionStrings.config"/>
</configuration>
But I get this error:
The configSource attribute is invalid.: The configSource '..\connectionStrings.config' is invalid. It must refer to a file in the same directory or in a subdirectory as the configuration file.
It works if we place the connectionStrings.config in same folder as the web.config or in a child folder. But that's not what we require.
Can anyone help us with this? Thanks in advance.
In my opinion, we could refer to this file by Adding Existing Item.
Then switch the “build action” to “content” and “copy to output directory” to “Always” in the property page of the referring file.
We could choose to add a file to the current project or a link to this file.
Finally, the file in other directory cannot work may be due to problems with read and write permissions to the file.
Feel free to let me know if there is anything I can help with.

Optimized bundles returning 404 when requesting from the website

I'm having this weird problem when I set:
BundleTable.EnableOptimizations = true;
When I try to open my website it just won't load, when I open Chrome's console I see the following message:
GET /localhost/bundles/scripts/angularjs/commonmodules?v=13-uWpwzN3U6kiHVssXRdpywHxrn09twvYKwoDVN3SU1 404 (Not Found)
However, if I try to open the link shown on chrome's console, it loads just fine, in other words, the link is found when I try to open it directly, but the server (IIS 7.5) returns a 404 when a page tries to link it through a tag.
Have anyone been through such a weird behavior?
The virtual paths for my bundles do not map for any existing file or directory, I include them using the following code:
var myBundle= new ScriptBundle("~/bundles/scripts/angularjs/bootstrapping");
bootstrapping.Include("~/app/app.js")
.Include("~/app/config.js")
.Include("~/app/config.exceptionHandler.js")
.Include("~/app/config.route.js");
bundles.Add(bootstrapping);
And I already tried to add the following lines on web.config's system.webServer:
<modules runAllManagedModulesForAllRequests="true">
<remove name="BundleModule" />
<add name="BundleModule" type="System.Web.Optimization.BundleModule" />
</modules>
I'm not sure if this may be related, but I'm using Umbraco v7 on this website, and this only happens if I set EnableOptimizations to "true".
If I remember correctly it's umbraco config related.
Locate the key umbracoReservedPaths (in appSettings) in your web.config and add the path to bundles there, like so:
<add key="umbracoReservedPaths" value="~/umbraco,~/install/,~/bundles/"/>

Adding custom section to web.config in ASP.NET 4

I've spent half of a day trying to understand why the following fails.
I can add section anywhere but never got it working like that ():
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<mysection />
<system.web>
<compilation debug="false" batch="false" targetFramework="4.0" />
</system.web>
<system.webServer>
<handlers>
</handlers>
</system.webServer>
</configuration>
I think the error related to .NET 4, because when you put section without pre-configuration in applicationHost.config it shows error with gray border saying that config is incorrect. That is what I expect. Then I add section definition and everything seems to work I can edit config from console - this means it is parsed correctly now.
But when I try to reach Application, it gives:
Parser Error Message: Unrecognized configuration section mysection
with a piece of config on yellow background.
Or do I need to write a module to consume that settings ? At the moment I do not have any, just a text in config.
following links will help you understand for this.
http://www.codeproject.com/Articles/32628/ASP-NET-Custom-Web-Configuration-Section
https://web.archive.org/web/20211020133931/https://www.4guysfromrolla.com/articles/032807-1.aspx
Regards,
Old topic but these links are very helpfull:
http://www.iis.net/learn/develop/extending-iis-configuration/configuration-extensibility
http://www.iis.net/learn/develop/extending-iis-configuration/extending-iis-schema-and-accessing-the-custom-sections-using-mwa
Edit (05/25/2016) :
The Details of how to store custom information in applicationHost.config file ... I hope this helps !
Note : These settings wont be visible on IIS Manager. There is a way to do that but thats beyond the scope of this response.
Requirement:
Need to extend the system.applicationHost/sites section of applicationHost.config file to allow a siteowner attribute at the site level. (IIS Does not allow us to do this by default). Nor can you manually edit the applicationHost.config file and add custom tags/attributes.
Steps:
Create a custom schema ( xml ) file under %windir%\system32\inetsrv\config\schema\ . File name: siteExtension_schema.xml
Include the custom elements that you want to eventually save in the applicationHost.config in that xml and save it with a appropriate name. The crucial thing to keep in mind is the sectionSchema tag.So when extending the schema of an existing section, simply create a element and set the name attribute to be the same as an existing section. In the schema file (see below), we have defined a with a name of "system.applicationHost/sites" - this is the same as the sectionSchema name in the default IIS_Schema.xml file in the Schema directory. So in essence you are instructing IIS to add these
<!-- Contents of %windir%\system32\inetsrv\config\schema\siteExtension_schema.xml -->
<configSchema>
<sectionSchema name="system.applicationHost/sites">
<collection addElement="site">
<attribute name="owner" type="string" />
<attribute name="ownerEmail" type="string" />
</collection>
</sectionSchema>
</configSchema>
Test the modifications by adding values for the "owner" and "ownerEmail" attributes that we included in step 2 above and then check the configuration file (applicationHost.config) to see the changes. Simply run the following command (must be elevated as Administrator) from the command line (uses appcmd ) to do so:
C:\> %windir%\system32\inetsrv\appcmd set site "Default Web Site" /owner:"John Contoso" /ownerEmail:"john#contoso.com"
To see if the configuration was applied, run the following command and check the output:
C:\> %windir%\system32\inetsrv\appcmd list site "Default Web Site" /config
<system.applicationHost>
<sites>
...
<site name="Default Web Site" id="1" siteOwner="John Contoso" siteOwnerEmail="john#contoso.com">
...
...
</site>
</sites>
</system.applicationHost>
To Read and Write your settings programmatically thru C# :
//this Will work with the ServerManager.OpenRemote("MyRemoteHostname") method also
using(var mgr = new ServerManager())
{
//Read
Console.WriteLine(mgr.Sites["Default Web Site"].Attributes["owner"].Value ); //Prints "John Contoso"
//Write
mgr.Sites["Default Web Site"].Attributes["owner"].Value = "New Owner";// Sets new value
mgr.CommitChanges(); // commits the changes to applicationHost.Config
}

Resources