Suppose I have the following <httpErrors>
collection in a web.config
:
<httpErrors>
</httpErrors>
Yep, nice 'n empty.
And in IIS 7, my HTTP errors page looks like this:
Beautiful! (I've highlighted 404 simply because that's the example I'll use in a sec).
Now, I run the following code:
errorElement["statusCode"] = 404;
errorElement["subStatusCode"] = -1;
errorElement["path"] = "/404.html";
httpErrorsCollection.Add(errorElement);
Lovely. I now have, as expected this in my web.config
:
<httpErrors>
<remove statusCode="404" subStatusCode="-1" />
<error statusCode="404" subStatusCode="-1" prefixLanguageFilePath="" path="/404.html" />
</httpErrors>
Couldn't be happier. Now, in IIS 7 my HTTP errors section looks, as expected, like below:
Life couldn't be sweeter at this point. Now, down the line, I want to programmatically revert my 404 error back to the state shown in the original screenshot. Logic dictates that I should remove
my new error:
httpErrorsCollection.Remove(errorElement);
But alas, if I do this, my web.config
looks a lot like this:
<httpErrors>
<remove statusCode="404" subStatusCode="-1" />
</httpErrors>
And my IIS looks a bit like this:
This is expected because of my web.config
- but how, using ServerManager
and all it's useful IIS 7 API, do I remove the httpError
element entirely and revert my web.config
back to:
<httpErrors>
</httpErrors>
Any ideas?
In IIS7 and above under Management section, we can see an icon named Configuration Editor, double click and expand to
Right click on Default path, under
Then restart the website
The changes will be reverted back
Well this is what I've found for this issue:
I get a list of elements as normal, then loop to find the one I want, and then call delete on the element. That's it and it works. I don't know if this existed when this question was asked, but it does now. You'll have to make sure you know that status code and substatus code.
I've bumped into this before. The only way I could make this work was to call
RevertToParent()
on thesystem.webServer/httpErrors
section and commit the changes before making any changes, e.g.:You have to commit after
RevertToParent() is called because the errors collection remains intact until
CommitChanges()` is called.You then have to re-add the saved copy of the local errors collection removing or updating the custom errors as they are re-added.
I've pasted a full working example below. The code works on the site root
web.config
but with a bit of tinkering you could add support forweb.config
files in subfolders: