How do you modify the web.config appSettings at runtime? - asp.net

I am confused on how to modify the web.config appSettings values at runtime. For example, I have this appSettings section:
<appSettings>
<add key="productspagedesc" value="TODO: Edit this default message" />
<add key="servicespagedesc" value="TODO: Edit this default message" />
<add key="contactspagedesc" value="TODO: Edit this default message" />
<add key="aboutpagedesc" value="TODO: Edit this default message" />
<add key="homepagedesc" value="TODO: Edit this default message" />
</appSettings>
Let's say, I want to modify the "homepagedesc" key at runtime. I tried ConfigurationManager and WebConfigurationManager static classes, but the settings are "read-only". How do I modify appSettings values at runtime?
UPDATE:
Ok, so here I am 5 years later. I would like to point out that experience has told me, we should not put any configuration that intentionally is editable at runtime in the web.config file but instead we should put it in a separate XML file as what one of the users commented below. This will not require any of edit of web.config file to restart the App which will result with angry users calling you.

You need to use WebConfigurationManager.OpenWebConfiguration():
For Example:
Dim myConfiguration As Configuration = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~")
myConfiguration.ConnectionStrings.ConnectionStrings("myDatabaseName").ConnectionString = txtConnectionString.Text
myConfiguration.AppSettings.Settings.Item("myKey").Value = txtmyKey.Text
myConfiguration.Save()
I think you might also need to set AllowLocation in machine.config. This is a boolean value that indicates whether individual pages can be configured using the element. If the "allowLocation" is false, it cannot be configured in individual elements.
Finally, it makes a difference if you run your application in IIS and run your test sample from Visual Studio. The ASP.NET process identity is the IIS account, ASPNET or NETWORK SERVICES (depending on IIS version).
Might need to grant ASPNET or NETWORK SERVICES Modify access on the folder where web.config resides.

Changing the web.config generally causes an application restart.
If you really need your application to edit its own settings, then you should consider a different approach such as databasing the settings or creating an xml file with the editable settings.

And if you want to avoid the restart of the application, you can move out the appSettings section:
<appSettings configSource="Config\appSettings.config"/>
to a separate file. And in combination with ConfigurationSaveMode.Minimal
var config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
config.Save(ConfigurationSaveMode.Minimal);
you can continue to use the appSettings section as the store for various settings without causing application restarts and without the need to use a file with a different format than the normal appSettings section.

2012
This is a better solution for this scenario (tested With Visual Studio 2008):
Configuration config = WebConfigurationManager.OpenWebConfiguration(HttpContext.Current.Request.ApplicationPath);
config.AppSettings.Settings.Remove("MyVariable");
config.AppSettings.Settings.Add("MyVariable", "MyValue");
config.Save();
Update 2018 =>
Tested in vs 2015 - Asp.net MVC5
var config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
config.AppSettings.Settings["MyVariable"].Value = "MyValue";
config.Save();
if u need to checking element exist, use this code:
var config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
if (config.AppSettings.Settings["MyVariable"] != null)
{
config.AppSettings.Settings["MyVariable"].Value = "MyValue";
}
else { config.AppSettings.Settings.Add("MyVariable", "MyValue"); }
config.Save();

I know this question is old, but I wanted to post an answer based on the current state of affairs in the ASP.NET\IIS world combined with my real world experience.
I recently spearheaded a project at my company where I wanted to consolidate and manage all of the appSettings & connectionStrings settings in our web.config files in one central place. I wanted to pursue an approach where our config settings were stored in ZooKeeper due to that projects maturity & stability. Not to mention that fact that ZooKeeper is by design a configuration & cluster managing application.
The project goals were very simple;
get ASP.NET to communicate with ZooKeeper
in Global.asax, Application_Start - pull web.config settings from ZooKeeper.
Upon getting passed the technical piece of getting ASP.NET to talk to ZooKeeper, I quickly found and hit a wall with the following code;
ConfigurationManager.AppSettings.Add(key_name, data_value)
That statement made the most logical sense since I wanted to ADD new settings to the appSettings collection. However, as the original poster (and many others) mentioned, this code call returns an Error stating that the collection is Read-Only.
After doing a bit of research and seeing all the different crazy ways people worked around this problem, I was very discouraged. Instead of giving up or settling for what appeared to be a less than ideal scenario, I decided to dig in and see if I was missing something.
With a little trial and error, I found the following code would do exactly what I wanted;
ConfigurationManager.AppSettings.Set(key_name, data_value)
Using this line of code, I am now able to load all 85 appSettings keys from ZooKeeper in my Application_Start.
In regards to general statements about changes to web.config triggering IIS recycles, I edited the following appPool settings to monitor the situation behind the scenes;
appPool-->Advanced Settings-->Recycling-->Disable Recycling for Configuration Changes = False
appPool-->Advanced Settings-->Recycling-->Generate Recycle Event Log Entry-->[For Each Setting] = True
With that combination of settings, if this process were to cause an appPool recycle, an Event Log entry should have be recorded, which it was not.
This leads me to conclude that it is possible, and indeed safe, to load an applications settings from a centralized storage medium.
I should mention that I am using IIS7.5 on Windows 7. The code will be getting deployed to IIS8 on Win2012. Should anything regarding this answer change, I will update this answer accordingly.

Who likes directly to the point,
In your Config
<appSettings>
<add key="Conf_id" value="71" />
</appSettings>
in your code(c#)
///SET
ConfigurationManager.AppSettings.Set("Conf_id", "whateveryourvalue");
///GET
string conf = ConfigurationManager.AppSettings.Get("Conf_id").ToString();

Try This:
using System;
using System.Configuration;
using System.Web.Configuration;
namespace SampleApplication.WebConfig
{
public partial class webConfigFile : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//Helps to open the Root level web.config file.
Configuration webConfigApp = WebConfigurationManager.OpenWebConfiguration("~");
//Modifying the AppKey from AppValue to AppValue1
webConfigApp.AppSettings.Settings["ConnectionString"].Value = "ConnectionString";
//Save the Modified settings of AppSettings.
webConfigApp.Save();
}
}
}

Related

Web.config settings not available when deploying WCF service to local IIS 10

I spent the last 2 hours trying to find an answer, unsuccessfull .... hope anyone can help.
I created a WCF service which I "deployed" to my local IIS 10 (on Windows 10).
This "deployment process" was performed by adding a new IIS web site (ASP.NET v4.6.2) in IIS manager. The physical path of this IIS site is the root of my WCF project (where SVC and web.config reside).
I can invoke the service and WSDL when calling it from SoapUI, and executiong stops at the breakpoint in my service handler method. So far, so good.
It does not see my web.config changes though. Upon debugging the code that tries to read the config values, I noticed the file path of the web.config file is: C:\Windows\Microsoft.NET\Framework\v4.0.30319\Config\web.config.
It seems to me that this is the "master" config of my .NET (runtime) environment.
The projects web.config file is available next to the SVC, and afaik everyone has access in IIS and on the file system. Am I missing something?
A couple of other things:
there are web.config transforms for debug and release; both are empty, and adding the entries to the debug version manually did not help
one of the other projects in the solution has a app.config, so the service can also be ran as console or windows service application (which both work)
Thanks in advance for any help!
I discovered the problem. This was partly due to the fact that I was maintaining someone else's code and overlooked some elementary stuff.
The configuration was read through this line of code:
Configuration rootWebConfig1 = WebConfigurationManager.OpenWebConfiguration(null);
As the variable name says, this will get the root web.config (in the .NET runtime folder).
When I made the following change:
Configuration config = WebConfigurationManager.OpenWebConfiguration("~");
it did see my settings. Afaik "~" means the root of the application, versus "/" means the root of the website (correct me if I'm wrong).
For completeness, my setting in the web.config looks like this:
<appSettings>
<add key="someFakeKey" value="someValue" />
</appSettings>
And the whole code-block to retrieve the setting:
Configuration config = WebConfigurationManager.OpenWebConfiguration("~");
if (config.AppSettings.Settings.Count > 0)
{
KeyValueConfigurationElement poliskluisServerSetting = config.AppSettings.Settings["someFakeKey"];
if (poliskluisServerSetting != null) _poliskluisserver = poliskluisServerSetting.Value;
}

No owin.Environment item was found in the context

Microsoft recently introduced new ASP.NET Identity - replacement for old (Simple)Membership. Unfortunately, I can't use this new membership system in my old project because it throws System.InvalidOperationException: No owin.Environment item was found in the context. This is a known bug, but Microsoft keeps silence about this issue. The easiest way to reproduce this bug - it's to create a new web application (MVC, WebForms or WebApi - doesn't matter) in VS 2013 (with Web Tools 2013 Preview Refresh) and then go to the login page. It will work. Then change namespace in your application to anything else than original namespace and login page will throw that error. Changing namespace back to original (the one you used at the creation of a project) will solve this problem.
It looks like .net stores somewhere something related to the original namespace, but I can't find what and where, it's not in the project folder. I know that stackoverflow is not a place for a bug reports, I just hoping that someone already found a solution for this issue or maybe people involved in the development of ASP.NET Identity will see this.
Most likely it cannot find the OWIN Startup class. The default convention for the Startup class is [AssemblyName].Startup. If you're no longer following that convention you'll need to specify the full name of your Startup class in the Web.Config.
The next release of Microsoft.Owin.Host.SystemWeb package now throws detailed exception messages when the Startup class cannot be found.
I had the same issue, it was fixed after making sure this line was in web.config:
<add key="owin:AutomaticAppStartup" value="true" />
I had the exact same error, but as it turned out I had another configuration problem in my web.config. My web.config was missing the attribute defaultLanguage="c#" in the compilation element under system.web.
In this case it will default to VB. So unless you have your Startup class written in VB you should change the default language to C#.
Not correct:
<compilation debug="true" optimizeCompilations="true" targetFramework="4.6.1">
This is correct (unless you use VB):
<compilation debug="true" defaultLanguage="c#" optimizeCompilations="true" targetFramework="4.6.1">
Cleaning ASP.NET temporary files helped me with this exact problem
I created two new projects called TesteMvc5.2 and TesteMvc5.0 and both of them didn't work at start
this is because the default namespace is different from the assembly name.
but after I put the line
<add key="owin:AppStartup" value="TesteMvc5._2.Startup, TesteMvc5.2" />
on the web.config it worked fine.
I tried everything mentioned on this page but nothing worked. Then I found out about a setting in IIS named owin:AutomaticAppStartup. You can find it in the Application Settings page of the IIS Manager for the Default Web Site. Check to see if that setting is true. If not set to true. This worked for me.
This is the website where I found the answer:
http://gotoanswer.stanford.edu/?q=Microsoft.Owin.Host.SystemWeb+and+still+getting+No+owin.Environment+item+was+found+in+the+context
If you happened to have copied the below config from MVC4, you should remove it from web.config
<add key="owin:AutomaticAppStartup" value="false" />
I had this same issue. I fixed it with the web.config.
However I had changed the assembly name and namespace and did not find the original assembly name anywhere anymore.
I then discovered that clean was not removing the original assembly from the bin.
Aftter deleting the bin litter, I was able to remove the web.config OWIN entry.
None of the above answers worked for me.
Turned out my project was missing the "Startup" class that contains the following:
using Microsoft.Owin;
using Owin;
[assembly: OwinStartupAttribute(typeof(NAMESPACE.Startup))]
namespace NAMESPACE
{
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
ConfigureAuth(app);
}
}
}
This file called "Startup.cs" is located on the root folder (~/) of your project.
My "Web.config" doesn't have any of this "Owin" configuration posted on the other replies.
Had same problem. Thanks for the shared solutions.
this..
<add key="owin.AppStartup" value="Namespace.Startup, Namespace"/>
<add key="owin:AutomaticAppStartup" value="false"/>
fixed for me
I have no idea why this works but it did!
My problem was in VS2013. In the WebConfig, debug was set to true and I got that error. When I set it to false it worked fine and then I reset to true and it continued to work OK!
At first when debug was true before changing to false, I put a break point in my StartUp code and it wasn't reached at all. After changing to false pressing save and then back to true the StartUp code was called and the program works like it should.
I experienced this error in an Optimizely (Episerver) solution where I had two feature branches using the same CMS database. In one feature branch I was working on a proof of concept using a visitor criterion. So I had created something like this:
public class SomeVisitorCriterionSettings : CriterionModelBase
{
public override ICriterionModel Copy()
{
return base.ShallowCopy();
}
}
[VisitorGroupCriterion(
Category = "Some category",
DisplayName = "My visitor criterion")]
public class SomeVisitorCriterion : CriterionBase<SomeVisitorCriterionSettings>
{
public override bool IsMatch(IPrincipal principal, HttpContextBase httpContext)
{
// match logic here..
}
}
And within Episerver -> CMS -> Visitor Groups I had created an instance of this visitor criterion. After switching to the other branch where this code did not exist, but the instance in the database did, the Owin exception was thrown.
Deleting the visitor criterion in the CMS resolved the issue, but I honestly have no idea why this sort of exception is thrown. I would love to know though..
I have tried all of the above suggestions, without success;
then reading the documentation at:
https://learn.microsoft.com/en-us/aspnet/aspnet/overview/owin-and-katana/owin-startup-class-detection
I understood that the error was in the call to the assembly in the Startup.cs file:
wrong code:
[assembly: OwinStartupAttribute(typeof([AssemblyName].Startup))]
right code:
[assembly: OwinStartup(typeof([AssemblyName].Startup))]
so, I fixed the error removing the word Attribute from OwinStartupAttribute
adding default language to compilation in web.config did it for me!

Asp.net Validation of viewstate MAC failed

I am receiving the following error at certain times on asp.net website.
Sys.WebForms.PageRequestManagerServerErrorException:
Validation of viewstate MAC failed.
If this application is hosted by a Web Farm or cluster,
ensure that <machineKey> configuration specifies the
same validationKey and validation algorithm.
AutoGenerate cannot be used in a cluster.
When page refresh goes,no problem.How can I solve this problem?
Microsoft says to never use a key generator web site.
Like everyone else here, I added this to my web.config.
<System.Web>
<machineKey decryptionKey="ABC123...SUPERLONGKEY...5432JFEI242"
validationKey="XYZ234...SUPERLONGVALIDATIONKEY...FDA"
validation="SHA1" />
</system.web>
However, I used IIS as my machineKey generator like so:
Open IIS and select a website to get this screen:
Double click the Machine Key icon to get this screen:
Click the "Generate Keys" link on the right which I outlined in the pic above.
Notes:
If you select the "Generate a unique key for each application"
checkbox, ",IsolateApps" will be added to the end of your keys. I had
to remove these to get the app to work. Obviously, they're not part
of the key.
SHA1 was the default encryption method selected by IIS and if you change it, don't forget to change the validation property on machineKey in the web.config. However, encryption methods and algorithms evolve so please feel free to edit
this post with the updated preferred Encryption method or mention it
in the notes and I'll update.
If you're using a web farm and running the same application on multiple computers, you need to define the machine key explicitly in the machine.config file:
<machineKey validationKey="JFDSGOIEURTJKTREKOIRUWTKLRJTKUROIUFLKSIOSUGOIFDS..." decryptionKey="KAJDFOIAUOILKER534095U43098435H43OI5098479854" validation="SHA1" />
Put it under the <system.web> tag.
The AutoGenerate for the machine code can not be used. To generate your own machineKey see this powershell script:
https://support.microsoft.com/en-us/kb/2915218#bookmark-appendixa
I had this problem, and for me the answer was different than the other answers to this question.
I have an application with a lot of customers. I catch all error in the application_error in global.asax and I send myself an email with the error detail. After I published a new version of my apps, I began receiving a lot of Validation of viewstate MAC failed error message.
After a day of searching I realized that I have a timer in my apps, that refresh an update panel every minute. So when I published a new version of my apps, and some customer have left her computer open on my website. I receive an error message every time that the timer refresh because the actual viewstate does not match with the new one. I received this message until all customers closed the website or refresh their browser to get the new version.
I'm sorry for my English, and I know that my case is very specific, but if it can help someone to save a day, I think that it is a good thing.
This solution worked for me in ASP.NET 4.5 using a Web Forms site.
Use the following site to generate a Machine Key (for example only use secure method in production): http://www.blackbeltcoder.com/Resources/MachineKey.aspx
Copy Full Machine Key Code.
Go To your Web.Config File.
Paste the Machine Key in the following code section:
<configuration>
<system.web>
<machineKey ... />
</system.web>
</configuration>
You should not see the viewstate Mac failed error anymore. Each website in the same app pool should have a separate machine key otherwise this error will continue.
Dear All with all respict to answers up there
there are case gives this error
when web.config value is
<httpCookies httpOnlyCookies="true" requireSSL="true"/>
and link is http not https
On multi-server environment, this error likely occurs when session expires and another instance of an application is resorted with same session id and machine key but on a different server. At first, each server produce its own machine key which later is associated with a single instance of an application. When session expires and current server is busy, the application is redirected like, via load balancer to a more operational server. In my case I run same app from multiple servers, the error message:
Validation of viewstate MAC failed. If this application is hosted by a
Web Farm or cluster, ensure that configuration specifies
the same validationKey and validation algorithm
Defining the machine code under in web.config have solve the problem.
But instead of using 3rd party sites for code generation which might be corrupted, please run this from your command shell:
Based on microsoft solution 1a, https://support.microsoft.com/en-us/kb/2915218#AppendixA
# Generates a <machineKey> element that can be copied + pasted into a Web.config file.
function Generate-MachineKey {
[CmdletBinding()]
param (
[ValidateSet("AES", "DES", "3DES")]
[string]$decryptionAlgorithm = 'AES',
[ValidateSet("MD5", "SHA1", "HMACSHA256", "HMACSHA384", "HMACSHA512")]
[string]$validationAlgorithm = 'HMACSHA256'
)
process {
function BinaryToHex {
[CmdLetBinding()]
param($bytes)
process {
$builder = new-object System.Text.StringBuilder
foreach ($b in $bytes) {
$builder = $builder.AppendFormat([System.Globalization.CultureInfo]::InvariantCulture, "{0:X2}", $b)
}
$builder
}
}
switch ($decryptionAlgorithm) {
"AES" { $decryptionObject = new-object System.Security.Cryptography.AesCryptoServiceProvider }
"DES" { $decryptionObject = new-object System.Security.Cryptography.DESCryptoServiceProvider }
"3DES" { $decryptionObject = new-object System.Security.Cryptography.TripleDESCryptoServiceProvider }
}
$decryptionObject.GenerateKey()
$decryptionKey = BinaryToHex($decryptionObject.Key)
$decryptionObject.Dispose()
switch ($validationAlgorithm) {
"MD5" { $validationObject = new-object System.Security.Cryptography.HMACMD5 }
"SHA1" { $validationObject = new-object System.Security.Cryptography.HMACSHA1 }
"HMACSHA256" { $validationObject = new-object System.Security.Cryptography.HMACSHA256 }
"HMACSHA385" { $validationObject = new-object System.Security.Cryptography.HMACSHA384 }
"HMACSHA512" { $validationObject = new-object System.Security.Cryptography.HMACSHA512 }
}
$validationKey = BinaryToHex($validationObject.Key)
$validationObject.Dispose()
[string]::Format([System.Globalization.CultureInfo]::InvariantCulture,
"<machineKey decryption=`"{0}`" decryptionKey=`"{1}`" validation=`"{2}`" validationKey=`"{3}`" />",
$decryptionAlgorithm.ToUpperInvariant(), $decryptionKey,
$validationAlgorithm.ToUpperInvariant(), $validationKey)
}
}
Then:
For ASP.NET 4.0
Generate-MachineKey
Your key will look like: <machineKey decryption="AES" decryptionKey="..." validation="HMACSHA256" validationKey="..." />
For ASP.NET 2.0 and 3.5
Generate-MachineKey -validation sha1
Your key will look like: <machineKey decryption="AES" decryptionKey="..." validation="SHA1" validationKey="..." />
WHAT DID WORK FOR ME
Search the web for "MachineKey generator"
Go to one of the sites found and generate the Machine Key, that will look like... (the numbers are bigger)
...MachineKey
validationKey="0EF6C03C11FC...63EAE6A00F0B6B35DD4B" decryptionKey="2F5E2FD80991C629...3ACA674CD3B5F068"
validation="SHA1" decryption="AES" />
Copy and paste into the <system.web> section in the web.config file.
If you want to follow the path I did...
https://support.microsoft.com/en-us/kb/2915218#AppendixA
Resolving view state message authentication code (MAC) errors
Resolution 3b: Use an explicit <machineKey>
By adding an explicit <machineKey> element to the application's Web.config file, the developer tells ASP.NET not to use the auto-generated cryptographic key. See Appendix A for instructions on how to generate a <machineKey> element.
http://blogs.msdn.com/b/amb/archive/2012/07/31/easiest-way-to-generate-machinekey.aspx
Easiest way to generate MachineKey - Ahmet Mithat Bostanci - 31 Jul 2012
You can search in Bing for "MachineKey generator" and use an online service. Honestly...
http://www.blackbeltcoder.com/Resources/MachineKey.aspx
my problem was this piece of javascript code
$('input').each(function(ele, indx){
this.value = this.value.toUpperCase();
});
Turns it was messing with viewstate hidden field so I changed it to below code and it worked
$('input:visible').each(function(ele, indx){
this.value = this.value.toUpperCase();
});
This error message is normally displayed after you have published your website to the server.
The main problem lies in the Application Pool you use for your website.
Configure your website to use the proper .NET Framework version (i.e. v4.0) under the General section of the Application Pool related to your website.
Under the Process Model, set the Identity value to Network Service.
Close the dialog box and right-click your website and select Advanced Settings... from the Manage Website option of the content menu. In the dialog box, under General section, make sure you have selected the proper name of the Application Pool to be used.
Your website should now run without any problem.
Hope this helps you overcome this error.
Validation of viewstate MAC failed. If this application is hosted by a web farm or cluster, ensure that <machineKey> configuration specifies the same validationKey and validation algorithm. AutoGenerate cannot be used in a cluster.
Answer :
<machineKey decryptionKey="2CC8E5C3B1812451A707FBAAAEAC9052E05AE1B858993660" validation="HMACSHA256" decryption="AES" validationKey="CB8860CE588A62A2CF9B0B2F48D2C8C31A6A40F0517268CEBCA431A3177B08FC53D818B82DEDCF015A71A0C4B817EA8FDCA2B3BDD091D89F2EDDFB3C06C0CB32" />
I had this same issue and it was due to a Gridview (generated from a vb code) on the page which had sorting enabled. Disabling Sort fixed my issue. I do not have this problem with the gridviews created using a SQLdatasource.
I am not sure how this happened but I started to get this error in my internal submit form pages. So when ever I submit something I'm getting this error. But the problem is this website is almost working 5-6 years. I don't remember I made an important change.
None of the solutions worked for me.
I have setup a machine key with the Microsoft script and copied into my web.config
I have executed asp.net regiis script.
aspnet_regiis -ga "IIS APPPOOL\My App Pool"
Also tried to add this code into the page:
enableViewStateMac="false"
still no luck.
Any other idea to solve this issue?
UPDATE:
Finally I solved the issue.
I had integrated my angular 4 component into my asp.net website.
So I had added base href into my master page. So I removed that code and it is working fine now.
<base href="/" />
There are another scenario which was happening for my customers. This was happening normally in certain time because of shift changes and users needed to login with different user.
Here is a scenario which Anti forgery system protects system by generation this error:
1- Once close/open your browser.
2- Go to your website and login with "User A"
3- Open new Tab in browser and enter the same address site. (You can see your site Home page without any authentication)
4- Logout from your site and Login with another User(User B) in second tab.
5- Now go back to the first Tab which you logged in by "User A". You can still see the page but any action in this tab will make the error.
Because your cookie is already updated by "User B" and you are trying to send a request by an invalid user. (User A)
<system.web>
<pages validateRequest="false" enableEventValidation="false" viewStateEncryptionMode ="Never" />
</system.web>
I have faced the similar issue on my website hosted on IIS. This issue generally because of IIS Application pool settings. As application pool recycle after some time that caused the issue for me.
Following steps help me to fix the issue:
Open App pool of you website on IIS.
Go to Advance settings on right hand pane.
Scroll down to Process Model
Change Idle Time-out minutes to 20 or number of minutes you don't want to recycle your App pool.
Then try again . It will solve your issue.
I've experienced the same issue on our project. This Microsoft support web page helped me to find the cause. And this solution helped to sort out the issue.
In my case the issue was around ViewStateUserKey as Page.ViewStateUserKey property had an incorrect value (Caused 4 in here). Deleting localhost certificates and recreating them by repairing IIS Expres as mentioned in here fixed the issue.
Thats worked for me
Just add it :
between
system.web section
<system.web>
</system.web>

Custom VirtualPathProvider not being used in IIS6

I added the following lines to Application_Start method in global.asax:
var provider = new TestVirtualPathProvider();
HostingEnvironment.RegisterVirtualPathProvider(provider);
Yet the 'TestVirtualPathProvider' is never used when deploying this application in IIS6 (it does in the ASP.NET Development Server).
Edit: the default path provider has always done its job correctly and served (non-embedded) views correctly. The problem is simply that I want to use my own path provider to provide embedded views. So, initially, I already had the following wildcard mapping configured:
Any possible reasons why this does not work in IIS6?
Are there any other factors (handlers for example) wich might influence the used VirtualPathProvider?
UPDATE: the fact that you want to handle extension-less URL's is an important point that's not mentioned in the question. Please see this page for help in setting up MVC with IIS 6: http://haacked.com/archive/2008/11/26/asp.net-mvc-on-iis-6-walkthrough.aspx. This should cover your scenario as well.
Most likely the same issue that I answered in this thread: http://forums.asp.net/t/995633.aspx
Basically, add this in your web.config:
<httpHandlers>
<add path="*" verb="GET,HEAD,POST" type="System.Web.StaticFileHandler" validate="true" />
</httpHandlers>
That other thread has some details that explain why this is necessary.
For the combination Custom VPP + IIS6 + Precompiled site, we need to add the VPP from AppInitailize();
public static class AppStart
{
public static void AppInitialize()
{
// code to be executed automatically by the framework
}
}
See also:
http://sunali.com/2008/01/09/virtualpathprovider-in-precompiled-web-sites/
I believe that you need to use an ISAPI filter in IIS6 to intercept URLs without extensions. Problem is that ISAPI will need to be done in c/c++.
IIS6 is configured to allow only certain extensions to be processed by the ASP.net pipeline.
To findout how you can redirct requests check out the post by DocV.

Conditional ConnectionString based on which folder the app is published to

I'm entering a parallel test and dev stage where I need to use one db for test and a different one for dev. How can I have the app choose which connection string to implement based on which physical folder it (the app) sits in?
I know there are SVN strategies to consider but this is small-scale enough to avoid 2 sperate code-bases. Would like to be able to publish the same VS project to either of my 2 directories without having to remind myself to change the connection string.
I'm running under IIS7 so perhaps it offers better control than conditionals in (and overrides) web.config. (or not)
thankx!
A word of advice:
I wouldn't base your connection string on your published folder. Down the road, the folder might change, and folks may not be aware that that determines which connection string you're using.
Instead, control it with a setting in your web.config file. Just add a setting that allows you to switch between production and dev databases. In fact, you could simply test for the presence of a debug mode setting. If that setting is there, you're targeting the development database; otherwise, you're targeting production.
The nice thing about that solution is that it doesn't depend on where you deploy the site, and you can document the setting in the Web.config file.
Hope this helps.
Edit for Clarity: By "a debug mode setting" I mean a setting that determines which database you're targeting, dev/production. Not whether your application is running in Debug mode, since the Framework already provides a function that does that. Also, you wouldn't necessarily remove the setting, since you'd want to keep it for documentation purposes. Rather, you'd comment it out.
You could e.g. create a <connectionStrings> container that contains a connection string for each folder your app could be in:
<connectionStrings>
<add name="Folder1" connectionString=".....(conn str. #1)...:" />
<add name="Folder2" connectionString=".....(conn str. #2)...:" />
....
<add name="Folder-n" connectionString=".....(conn str. #n)...:" />
</connectionStrings>
and then just pick the right one, depending on where your app starts up from.
Marc
Get a unique string for the application, perhaps something like:
string folder = Regex.Match(Server.MapPath("~"), #"\(.+?)\$").Groups[0].Value;
Then use the string to get a value from the web.config:
ConnectionStringSetting connectionString = ConfigurationManager.ConnectionStrings["ConnectionString." + folder] ?? ConfigurationManager.ConnectionStrings["ConnectionString"];
In the web.config you can add several connection strings with the folder names appended for each dev site, and a default connection string with just the name and no folder.
I usually put the connection strings into a separate config file and reference them from the main web.config using configSource:
In web.config:
<?xml version="1.0"?>
<configuration>
<!-- connection strings are located in an external config
file to facilitate deployment in various environments -->
<connectionStrings configSource="connections.config"></connectionStrings>
</configuration>
In connections.config:
<?xml version="1.0"?>
<connectionStrings>
<add name="ConnectionName" connectionString="[your connection string]"/>
</connectionStrings>
Once deployed, I usually exclude connections.config from future deployments (unless it should be changed, that is).

Resources