Edit Web.Config - "System.Net" Section Programmatically? - c#

I want to change the "system.net" section in web.config. I want to add or remove defaultProxy tag according to a variable in runtime.
<defaultProxy enabled="true" useDefaultCredentials="false">
<module type = "XXX.Utils.YYProxy, XXX" />
</defaultProxy>
I know, there are related posts editing web.config, but they all related with ConnectionStringsSection or AppSettingsSection. There are specific classes about them in System.Configuration package, but I did not find any class related with "system.net".
Do you know any quick way to handle this? Thanks in advance

I found a way to do this. I enable or disable the defaultProxy tag with following code:
Configuration config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
NetSectionGroup netSection = (NetSectionGroup)config.GetSectionGroup("system.net");
if (string.IsNullOrEmpty(model.ProxyUrl))
netSection.DefaultProxy.Enabled = false;
else
netSection.DefaultProxy.Enabled = true;
The key point was casting the SectionGroup to NetSectionGroup class.

Instead of removing the defaultProxy element from web.config, I recommend that, in your code, you override the proxy that is used based on the value assigned to the variable to which you refer.
For example:
WebRequest request = WebRequest.Create("http://stackoverflow.com/");
if(variable == "some expected value to override default proxy") {
//by setting the Proxy property of the Request object to a new WebProxy class, you override the default
request.Proxy = new WebProxy("http://someproxyserver.com:80", true);
}
Of course, I'd need to see more of your code to give a more complete answer.
Hope this helps!

Related

Programmatically edit the SslFlags in the web.config on an IIS site

On IIS, I have a site on which I wish to edit the SslFlags.
I want to have these flags being set in the web.config at the site level instead of applicationHost.config.
I managed to have the UI of IIS to behave as expected by declaring the access section in the web.config, and allowing the override of the access section by editing applicationHost.config with the following element:
<section name="access" overrideModeDefault="Allow" />
Editing the SslFlags through the UI will edit the web.config file as expected. The section is not locked and the overridden value is considered.
However, when using the Microsoft.Web.Administration assembly to read and edit these flags by using the following code, the values which are considered are the ones of applicationHost.config, both when reading and editing.
In that first example, I used GetWebConfiguration to get the Configuration.
var serverManager = ServerManager.OpenRemote(serverName);
// Try with GetWebConfiguration
Configuration config = serverManager.GetWebConfiguration(sitename);
ConfigurationSection accessSection = config.GetSection(
"system.webServer/security/access",
sitename);
also, same applies if I retrieve the configuration with GetApplicationHostConfiguration:
config = serverManager.GetApplicationHostConfiguration();
accessSection = config.GetSection(
"system.webServer/security/access",
sitename);
I feel like I'm missing something obvious here, but I can't seem to access the values of the SslFlags in Web.config, how can I achieve that?
The first thing I would recommend is to only unlock sections for the specific web site or application that you want to allow overriding the values. For that you can do it quite easily using AppCmd.exe, for example:
C:\Windows\System32\inetsrv\appcmd.exe unlock config "Default Web Site/" /section:system.webServer/security/access -commit:apphost
Once you do that, then you can use the following code:
using(ServerManager serverManager = new ServerManager()) {
Configuration config = serverManager.GetWebConfiguration("Default Web Site");
ConfigurationSection accessSection = config.GetSection("system.webServer/security/access");
accessSection["sslFlags"] = #"SslRequireCert";
serverManager.CommitChanges();
}

How to remove X-AspNetMvc-Version from header response without touching source code file (Global.asax.cs)?

I need to disable the X-AspNetMvc-Version from the response header of a large number of applications. The server where the applications are hosted has just the content and config files Global.asax, web.config, app.config for the application and source code files (*.cs) reside with some other team.
I could only find the solution as adding
MvcHandler.DisableMvcResponseHeader = true;
to Global.asax.cs.
Any alternative solution(s) that involves working with any config file(s)?
Set enableVersionHeader to false in your web.config is an alternate, I would prefer the web.config change to a handler solution like you have, obviously, since you will not need to access global.asax.cs to make the change:
just copy this line into the web.config’s <system.web> section:
<httpRuntime enableVersionHeader="false" />
http://msdn.microsoft.com/en-us/library/system.web.configuration.httpruntimesection.enableversionheader(v=vs.110).aspx
http://madskristensen.net/post/Remove-the-X-AspNet-Version-header
Unfortunately the only way is to use the following code in your Global.asax:
MvcHandler.DisableMvcResponseHeader = true;
This is an old post but no marked answer. I was able to achieve this using the code below. In your global.asax.cs we can remove any header.
protected void Application_PreSendRequestHeaders()
{
if (HttpContext.Current != null)
{
HttpContext.Current.Response.Headers.Remove("x-aspnet-version");
}
}

get reference to the ASP.NET web.config customErrors section

I'm trying to obtain a reference to the web.config customErrors section. When I use the following code I always get a null. I don't have this problem when I get a reference to a custom section that I've created so I'm a bit dumbfounded why this won't work.
CustomErrorsSection customErrorSection =
ConfigurationManager.GetSection("customErrors") as CustomErrorsSection;
I've also tried this:
CustomErrorsSection customErrorSection =
WebConfigurationManager.GetSection("customErrors") as CustomErrorsSection;
I've also tried this:
CustomErrorsSection customErrorSection =
WebConfigurationManager.GetWebApplicationSection("customErrors") as CustomErrorSection;
EDIT:
ARGH! Such is the case with most things I figured out the answer right after asking the question.
This works for me:
System.Configuration.Configuration configuration = WebConfigurationManager.OpenWebConfiguration("/");
CustomErrorsSection customErrorsSection = (CustomErrorsSection)configuration.GetSection("system.web/customErrors");
Or more simply like this:
CustomErrorsSection customErrors = (CustomErrorsSection) WebConfigurationManager.OpenWebConfiguration("/").GetSection("system.web/customErrors");
This also works:
CustomErrorsSection customErrorsSection = ConfigurationManager.GetSection("system.web/customErrors") as CustomErrorsSection;
So I guess I understand now why I had the problem in the first place. I had incorrectly thought that I could get a reference to the customErrors section by trying to GetSection("customErrors") but I had failed to tell it what root section it lived in and I was basing my attempts on the fact that I knew how to get a custom section when I failed to realize that my custom section was the root of the section so I did not have to prepend something like system.Web/ in front of it when I called GetSection().
Try this:
var configuration = WebConfigurationManager.OpenWebConfiguration("~/Web.config");
// Get the section.
CustomErrorsSection customErrors =
(CustomErrorsSection)configuration.GetSection("system.web/customErrors");
More on the subject here: CustomError Class

Checking CustomErrors turned on in Code

Is it possible to check weather custom errors is turned on or off in the code on web application runtime.
I've figured out how to do it it's in...
HttpContext.Current.IsCustomErrorEnabled
You can use WebConfigurationManager.OpenWebConfiguration to obtain the configuration for the website, then use that to get the custom errors block:
Configuration configuration =
WebConfigurationManager.OpenWebConfiguration(null);
CustomErrorsSection customErrorsSection =
configuration.GetSection("system.web/customErrors") as CustomErrorsSection;
Response.Write(customErrorsSection.Mode.ToString());
OpenWebConfiguration(null) or HttpContext.Current.IsCustomErrorEnabled(true) gave me false information, this however worked great
Copy paste:
public static CustomErrorsMode GetRedirectMode()
{
Configuration config = WebConfigurationManager.OpenWebConfiguration("/");
return ((CustomErrorsSection)config.GetSection("system.web/customErrors")).Mode;
}

Get values from the web.config section in an app.config file?

I'm trying to unit test values that will eventually wind up in a web.config file. In my test project, I created an app.config file with a web.config section to hold the settings. In a normal situation, I would call System.Configuration.ConfigurationSettings.AppSettings, but in this case, that doesn't work. I saw this question, which is very similar, but doesn't address how to get the NameValueCollection out of the config file. Here is an example of the config file:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.web>
<membership defaultProvider="CustomMembershipProvider">
<providers>
<clear/>
<add
name="CustomMembershipProvider"
applicationName="SettlementInfo"
enablePasswordRetrieval="false"
enablePasswordReset="false"
requiresQuestionAndAnswer="true"
writeExceptionsToEventLog="true" />
</providers>
</membership>
</system.web>
</configuration>
Has anyone dealt with this before?
I guess I'm confused here; it looks like you're trying to test that ASP.NET is using your custom membership provider appropriately. Correct?
If so, I'm 99.999% sure that you cannot unit test this using the MS framework; you must integration test it by deploying it to the webserver (or running Cassini in VS) and typing a username/password into your login page.
Now, it's possible I've misunderstood your request. If so, let me know and I'll edit my answer accordingly.
Edit:
For right now, I'm really just trying
to test the NameValue pairs coming out
of the config file, to make sure that
if the values aren't present, my
defaults are being applied. In other
words, I want to try to pull
applicationName, and verify that it
equals "SettlementInfo", and so on.
After that, I will be using
integration testing to ensure that
ASP.NET is using the custom framework
in place of the default one. Does that
make sense?
I need more than a comment to reply, so I'm editing. If I read you correctly, you are wanting to unit test your program to ensure that it deals with configuration correctly, yes? Meaning you want to ensure that your code grabs, for example, the correct AppSettings key and handles a null value therein, correct?
If that's the case, you're in luck; you don't need an app.config or web.config at all, you can set the values you need as part of your test setup.
For example:
[TestMethod]
public void Test_Configuration_Used_Correctly()
{
ConfigurationManager.AppSettings["MyConfigName"] = "MyConfigValue";
MyClass testObject = new MyClass();
testObject.ConfigurationHandler();
Assert.AreEqual(testObject.ConfigurationItemOrDefault, "MyConfigValue");
}
[TestMethod]
public void Test_Configuration_Defaults_Used_Correctly()
{
// you don't need to set AppSettings for a non-existent value...
// ConfigurationManager.AppSettings["MyConfigName"] = "MyConfigValue";
MyClass testObject = new MyClass();
testObject.ConfigurationHandler();
Assert.AreEqual(testObject.ConfigurationItemOrDefault, "MyConfigDefaultValue");
}
I believe you only have access to the webconfig file while your application is actually beeing started up. The solution is rather easy -> "Fake" your config. Use a NameValueCollection and use that instead:
private static NameValueCollection CreateConfig()
{
NameValueCollection config = new NameValueCollection();
config.Add("applicationName", "TestApp");
config.Add("enablePasswordReset", "false");
config.Add("enablePasswordRetrieval", "true");
config.Add("maxInvalidPasswordAttempts", "5");
config.Add("minRequiredNonalphanumericCharacters", "2");
config.Add("minRequiredPasswordLength", "6");
config.Add("requiresQuestionAndAnswer", "true");
config.Add("requiresUniqueEmail", "true");
config.Add("passwordAttemptWindow", "10");
return config;
}
Now you could easily pass that collection into your class that parses data from it.
You should be able to use the ConfigurationManager.GetSection() method to pull out whatever you want.
Actually, if you are using NUnit, you can stick that in an App.config in your test project.
Then add this line to your Post-build event:
copy /Y “$(ProjectDir)App.config” “$(TargetDir)$(TargetFileName).config”
When you create the new provider in your tests, NUnit will pass the values in your app.config to the provider in the initialize method.
Why not just stick it in the web.config file?

Categories