ASP.NET does not attempt to open web.config file? - asp.net

I am trying to get my .aspx page to read from its web.config file. Code that works on other servers does not work as expected on one particular server (all machines involved are W2K3 R2 SP2).
A snippet of the .aspx is
<body>
<form id="form1" runat="server">
<div>
<asp:Label runat="server" Text="" ID="lblTime" /><br />
Value of myConfigTest is '<asp:Label ID="lblValue" runat="server" Text=""/>'
</div>
</form>
</body>
The code is here:
using System;
using System.Web.Configuration;
namespace configTestWeb
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
lblTime.Text = DateTime.Now.ToLongTimeString();
string value = WebConfigurationManager.AppSettings["myConfigTest"];
lblValue.Text = value;
}
}
}
And my web.config file is set thusly:
<?xml version="1.0"?>
<configuration>
<appSettings>
<add key="myConfigTest" value="This is a test"/>
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.0" />
</system.web>
</configuration>
In an attempt to troubleshoot I setup ProcMon to filter on web.config and hit the page from a browser. The output is
1:06:04 PM
Value of myConfigTest is ''
But the really strange thing is that ProcMon never reports an attempt to access the file! If I right-click on the virtual directory in IIS and select Properties | ASP.NET | Edit Configuration I can see web.config being accessed with ~65 entries in ProcMon, and the appSetting is reported correctly in the ASP.NET Configuration Settings dialog.
I believe I've ruled out ACL's as an issue by
a) Setting the entire directory tree that the .aspx and web.config are in to Everyone | Full Permissions
b) ProcMon would report failed attempts to open the file if permissions were the issue
In desperation I uninstalled / reinstalled ASP.NET 4.0.
It may be noteworthy that reading configuration from an .exe works perfectly on that server using
string value = System.Configuration.ConfigurationManager.AppSettings[key];
This issue appears across multiple virtual directories.
So my question is, what might be preventing this one server from being able to read web.config files?

Rather than going to trouble of using ProcMon try doing a simpler test: Edit web.config file to enable the trace feature, then access website and see if it shows the request trace.
Add this to your web.config inside of system.web node:
<trace
enabled="true"
requestLimit="10"
pageOutput="false"
traceMode="SortByTime"
localOnly="false"
/>
By default changes to web.config (when file is saved/written to disk) will restart the ASP.NET application pool. These options can be changed, however, so if you do not see a change in your web app behavior after modifying web.config you can also try to stop and restart the service, or trigger an app pool recycle by using task manager to kill the aspnet_wp.exe process (I think this is what it is called in 2k3, if not try w3wp.exe instead), then make another request (refresh browser) to the web app and it IIS should start the app pool for ya.
If the changes (toggling between trace enabled=true and enabled=false) are not visible after saving web.config, but ARE visible after forcing stop/restart, then your IIS on that box may not have the option to restart app pool when configuration changes (don't have 2k3 in front of me, but in IIS 7 it is under Application Pools > Advanced Options > Recycling > "Disable Recyling for Configuration Changes" -- it is one of those annoying double-negative options, so "false" means recycle after config changes, and "true" means don't).
Update:
Dang, looks like IIS6 doesn't have that "for Configuration changes" option in the Recycling tab of the App pool properties sheet. Sorry, not sure where this setting is stored, doesn't appear to be in machine.config or web.config tho, so probably whatever IIS uses internally for the metabase stuff (registry maybe?)
If you try the trick for toggling trace and you don't see any effects, did you verify you are editing the correct web.config file?

Related

asp.net uploading image to server

I am uploading image to the server in an asp.net page.Here is the code..
Code:
protected void Button2_Click1(object sender, EventArgs e)
{
//resimyolu = "~/r/" + FileUpload1.FileName;
FileUpload1.SaveAs(Server.MapPath("~/r/a.png"));
FileUpload1.SaveAs("d:/upresim/a.png");
Image1.ImageUrl = "~/r/a.png";
}
the 'r' folder is the image folder in my project.when I add a picture to the 'r' folder at runtime,it works succesfully on local IIS ,but when I publish my project and host it on a server(remote server) the web page is opening in the browser ,but when I click button2 to add client image(which client user selected from his computer) to the project an error appears like below..
Runtime Error
Description: An application error occurred on the server. The current custom error settings for this application prevent the details of the application error from being viewed remotely (for security reasons). It could, however, be viewed by browsers running on the local server machine.
Details: To enable the details of this specific error message to be viewable on remote machines, please create a <customErrors> tag within a "web.config" configuration file located in the root directory of the current web application. This <customErrors> tag should then have its "mode" attribute set to "Off".
As suggested in the error message, disable the custom errors on your web.config to see what's the issue.
<configuration>
<system.web>
<customErrors mode="Off"/>
</system.web>
</configuration>
The problem is this line.
FileUpload1.SaveAs("d:/upresim/a.png");
Change it to will help.
FileUpload1.SaveAs("d:\\upresim\\a.png");
Avoid using such hardcoded paths if your code. You will face issues when you change machines. Server.MapPath is always a better way to go. If you do not want to save in your web dir, you should always take the base path from configuration.

Web.config Custom Errors mode Conflict

I have a great and important problem with Web.Config, I need to see the Error of my page and resolve it in asp.net web form and web config, but when Error Occurred, I see another error and I see this Message :
customErrors mode to Off or On Or RemoteOnly,
I set this property Off, but do not show error and say again please set attribute to On your CustomError.
when I set mode to On,say Please set customErrors mode to On Again.
When you're having issues with configuration, make sure that your
settings isn't overridden.
In this case, your server might have a configuration <deployment retail="true" /> that overrides application settings and disables trace output, custom errors, and debug capabilities.
Change the value to "false"
<deployment retail="false" />
MSDN Link
Make sure you nest the customErrors tag somewhere inside your <system.web> tag like this:
<system.web>
<customErrors mode="Off" />
</system.web>
From your description it's already likely it was placed there by you or automatically generated another way. Also try setting to On and restart the Application pool. You can do this by simply modifying web.config file by adding a break return or even just hit the space key, as long as you've made a change. Now re-upload making sure this is your second time with the customErrors mode was set to On. Hopefully you can now view your custom error page.
If you are still having problems, and have access to your web site from IIS Manager try editing the .NET Error Pages in Features view. That will also do the same thing, providing your custom error page is in the correct directory for the web.config file to access.
First, you can set CustomErrors mode from "RemoteOnly" to "off"
<customErrors mode="Off"></customErrors>
Second, You can check the global.asax.maybe you create Response.Redirect as same as defaultRedirect in customError. you can check more detail in here ASP.NET customErrors with mode=remoteOnly and global.asax handling exceptions
and the last,maybe you create two system.web in your webconfig. You should only have one in your config file.please check again your webconfig.
and dont forget <compilation debug="true"/>
To show the error for debugging and NOT showing an custom error page you do not need a defaultRedirect and simply having this should then output the debug / exception information:
<system.web>
<customErrors mode="On" />
</system.web>
NOTE: Ensure that On starts with an upper-case O. By changing the web.config this should (by default) recycle your app pool and be picked up straight away.
Here is sample code how you can display exceptions on custom page.
First create Default.aspx with button:
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Throw Error" />
Add following code for button click event:
protected void Button1_Click(object sender, EventArgs e)
{
throw new Exception("Sample Exception on my Page");
}
Second create ErrorPage.aspx with label:
<asp:Label ID="Label1" runat="server" Text=""></asp:Label>
And code for error page:
protected void Page_Load(object sender, EventArgs e)
{
Exception ex = Server.GetLastError();
if (ex != null && ex.InnerException != null)
{
Label1.Text = string.Format("An error occured: {0}", ex.InnerException.Message);
}
}
And finally place following configuration in web.config:
<system.web>
<customErrors mode="On" defaultRedirect="~/ErrorPage.aspx" redirectMode="ResponseRewrite" />
</system.web>
Compile and start with Default.aspx. Click your button and error will be shown on your custom page.
Happy coding!
I just wanted to comment here, but I do not have enough point to comment, Can we see the actual, page that produces the error and see the entire web.config? you can blur out the connectionstrings and such so as not to give any passwords away.
But with what I see,
I think from what you are saying you are using IIS Express debugging on local machine.
I would done IIS Express, or ctrl+F5 the page to see if the site is just not cached.
setting the custom errors to Off will show you the debug message - NOTE the "O" in Off must be capitalized with lower case of the f's. looks like you have this, but worth mentioning
Custom Errors Off - Specifies that custom errors are disabled. This allows display of detailed errors.
I've never seen it say set to On. I've seen it say set customeErrors to off which will give you detailed errors. Set it to off and then add the actual error message you see to this post. Are you positive your not getting a different message like a 404 error?
From what I can see, you don't have the <customErrors mode="Off" /> as the first node in the <system.web> node.
If I were to guess, you have the customErrors node inside a <compilation targetFramework="x.x"> node.
You probably have the applicationpool set to another version of the .NET framework than the application is written in. Make sure the <customErrors mode="Off" /> node is the first inside the <system.web> node, then it will most likely give you the detailed errormessage.
removing this line works for me!
<customError />
Many hosting companies actually override the settings from your web.config file by theirs. You can usually set these concrete attributes in the web host's dashboard for the website.
If you tell us the concrete web hosting you are using, we should be able to assist better with concrete steps.
Set the mode to On, save the web.config then refresh or restart the IIS and make sure the mode is still set to On after saved. Browse to it again, it should show the error...

How to enable/disable logging on ASP.NET

I'm trying to create a setup in my ASP.NET website that allows me to enable/disable logging while the application is running at any point. I figure some of you have already done such a thing.
Here's the gist of what i'm trying to do:
if(ShouldBeLogging)
logger.Info("helloooooo there");
So how would you set up the boolean value ShouldBeLogging to be able to be turned on/off while the website is running without getting any serious performance drawbacks(seeing how its going to be accessed frequently)?
I was thinking about putting something in the web.config, but wouldn't a change to that kick my user sessions if i wanted to turn it on?
Thanks!
I decided to go with log4net which supports this exact functionality. You can put a line in your assemblyinfo.cs like:
[assembly: log4net.Config.XmlConfigurator(ConfigFile = "config\\log4net.config", Watch = true)]
which will tell it to watch the config file for changes. then you can set the level node in the config xml at any time during the program's execution and the logging will be turned on/off, as long as you're using the following checks in your code:
if(log.IsDebugEnabled)
log.Debug("write a debug message to the logger");
see http://logging.apache.org/log4net/release/manual/internals.html for more info.
The built in diagnostics/tracing might be the best fit for your needs, i.e. see
http://www.beansoftware.com/ASP.NET-Tutorials/Tracing-ASP.NET.aspx
sample for web.config:
<configuration>
<appSettings/>
<connectionStrings/>
<system.web>
<compilation debug="false" />
<authentication mode="Windows" />
<trace enabled ="true" pageOutput ="false" requestLimit ="20" traceMode ="SortByTime " />
</system.web>
Yes, a change to the web.config will result in the application restarting itself, and session being lost depending on your session store.
The performance overhead of a boolean check is minimum, but its a maintenance nightmare.
Why don't you just use Enterprise Library Logging Application Block, which is already externally configurable? A reference for what you are trying to do would be here Checking Filter Status before Logging
If you decide you really want to toggle logging via if checks a simple psuedo solution is to add a value to your web.config appSettings
<appSettings>
<add key="DiagnosticLogging" value="true" />
</appSettings>
And then in your Global Page
public static readonly Boolean LoggingEnabled { get;}
Application_Start(..){
string log = ConfigurationSettings.AppSettings["DiagnosticLogging"];
LoggingEnabled = false;
if(!string.IsNullOrEmpty(log)){
if(!boolean.TryParse(out LoggingEnabled )){
//bad application setting.. handle
}
}
}

<httpRuntime requestValidationMode="2.0" /> doesn't work (using IIS 6.0)

I'm getting errors with an application on our test web server, which has .NET 4.0 installed, when I input HTML into a form. I get the usual errors of:
A potentially dangerous Request.Form value was detected from the
client
This is being caused by the change in .NET 4.0 that disables switching off automatic validation for HTML input. I can fix this on my local development machine by adding the
<httpRuntime requestValidationMode="2.0" />
directive to the <system.web> section of my root web.config, and .NET then honours the <pages validateRequest="false" /> directive that's in the same root web.config. Strangely, I needed to restart IIS on my local machine (which is version 5.1) for this change to work.
When I deploy the root web.config to our test server however, I'm still getting the validation errors. I've tried using run > iisreset, stopping and starting IIS (which is version 6.0 on the test server), and I've even restarted the server to fully clear out .NET. My application is definitely picking up the new root web.config (I've tested this), however the <httpRuntime requestValidationMode="2.0" /> directive seems to just be ignored.
My application is configured as a .NET 4.0 application on both my local machine and on the test server. I've tried rebuilding the application and redeploying it to the test web server. Can anyone suggest what I need to do to get this working?
Thanks in advance, Chris
If you are using MVC3, Try adding a global filter in Global.asax.cs.
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new ValidateInputAttribute(false));
}

How to increase request timeout in IIS?

How to increase request timeout in IIS 7.0? The same is done under application tab in ASP configuration settngs in IIS 6.0. I am not able to find the asp.net configuration section in IIS 7.0
Add this to your Web Config
<system.web>
<httpRuntime executionTimeout="180" />
</system.web>
https://msdn.microsoft.com/en-us/library/e1f13641(v=vs.85).aspx
Optional TimeSpan attribute.
Specifies the maximum number of seconds that a request is allowed to
execute before being automatically shut down by ASP.NET.
This time-out applies only if the debug attribute in the compilation
element is False. To help to prevent shutting down the application
while you are debugging, do not set this time-out to a large value.
The default is "00:01:50" (110 seconds).
In IIS Manager, right click on the site and go to Manage Web Site -> Advanced Settings. Under Connection Limits option, you should see Connection Time-out.
To Increase request time out add this to web.config
<system.web>
<httpRuntime executionTimeout="180" />
</system.web>
and for a specific page add this
<location path="somefile.aspx">
<system.web>
<httpRuntime executionTimeout="180"/>
</system.web>
</location>
The default is 90 seconds for .NET 1.x.
The default 110 seconds for .NET 2.0 and later.
In IIS >= 7, a <webLimits> section has replaced ConnectionTimeout, HeaderWaitTimeout, MaxGlobalBandwidth, and MinFileBytesPerSec IIS 6 metabase settings.
Example Configuration:
<configuration>
<system.applicationHost>
<webLimits connectionTimeout="00:01:00"
dynamicIdleThreshold="150"
headerWaitTimeout="00:00:30"
minBytesPerSecond="500"
/>
</system.applicationHost>
</configuration>
For reference: more information regarding these settings in IIS can be found here. Also, I was unable to add this section to the web.config via the IIS manager's "configuration editor", though it did show up once I added it and searched the configuration.
Below are provided steps to fix your issue.
Open your IIS
Go to "Sites" option.
Mouse right click.
Then open property "Manage Web Site".
Then click on "Advance Settings".
Expand section "Connection Limits", here you can set your "connection time out"
I know the question was about ASP but maybe somebody will find this answer helpful.
If you have a server behind the IIS 7.5 (e.g. Tomcat). In my case I have a server farm with Tomcat server configured.
In such case you can change the timeout using the IIS Manager:
go to Server Farms -> {Server Name} -> Proxy
change the value in the Time-out entry box
click Apply (top-right corner)
or you can change it in the cofig file:
open %WinDir%\System32\Inetsrv\Config\applicationHost.config
adjust the server webFarm configuration to be similar to the following
Example:
<webFarm name="${SERVER_NAME}" enabled="true">
<server address="${SERVER_ADDRESS}" enabled="true">
<applicationRequestRouting httpPort="${SERVER_PORT}" />
</server>
<applicationRequestRouting>
<protocol timeout="${TIME}" />
</applicationRequestRouting>
</webFarm>
The ${TIME} is in HH:mm:ss format (so if you want to set it to 90 seconds then put there 00:01:30)
In case of Tomcat (and probably other servlet containers) you have to remember to change the timeout in the %TOMCAT_DIR%\conf\server.xml (just search for connectionTimeout attribute in Connector tag, and remember that it is specified in milliseconds)
Use the below Power shell command to change the execution timeout (Request Timeout)
Please note that I have given this for default web site, before using
these please change the site and then try to use this.
Set-WebConfigurationProperty -pspath 'MACHINE/WEBROOT/APPHOST/Default Web Site' -filter "system.web/httpRuntime" -name "executionTimeout" -value "00:01:40"
Or, You can use the below C# code to do the same thing
using System;
using System.Text;
using Microsoft.Web.Administration;
internal static class Sample {
private static void Main() {
using(ServerManager serverManager = new ServerManager()) {
Configuration config = serverManager.GetWebConfiguration("Default Web Site");
ConfigurationSection httpRuntimeSection = config.GetSection("system.web/httpRuntime");
httpRuntimeSection["executionTimeout"] = TimeSpan.Parse("00:01:40");
serverManager.CommitChanges();
}
}
}
Or, you can use the JavaScript to do this.
var adminManager = new ActiveXObject('Microsoft.ApplicationHost.WritableAdminManager');
adminManager.CommitPath = "MACHINE/WEBROOT/APPHOST/Default Web Site";
var httpRuntimeSection = adminManager.GetAdminSection("system.web/httpRuntime", "MACHINE/WEBROOT/APPHOST/Default Web Site");
httpRuntimeSection.Properties.Item("executionTimeout").Value = "00:01:40";
adminManager.CommitChanges();
Or, you can use the AppCmd commands.
appcmd.exe set config "Default Web Site" -section:system.web/httpRuntime /executionTimeout:"00:01:40"
For AspNetCore, it looks like this:
<aspNetCore requestTimeout="00:20:00">
From here

Resources