Asp.Net – A potentially dangerous Request.Form value was detected from the client in asp.net

Yesterday, I was working in CMS engine in asp.net where I had to allow user to format the content in Rich Text Editors using Tiny Mice editor. but when I click on submit button asp.net raised an exception for “A potentially dangerous Request.Form value was detected from the client”.

Error:
Server Error in ‘ASP.Net’ Application.

A potentially dangerous Request.Form value was detected from the client (txtContent.Text=”<p>Hello</p>”).

Exception Details:
System.Web.HttpRequestValidationException: A potentially dangerous Request.Form value was detected from the client (TextBox1=”<p>Hello</p>”).

Description:
Request Validation has detected a potentially dangerous client input value, and processing of the request has been aborted. This value may indicate an attempt to compromise the security of your application, such as a cross-site scripting attack. You can disable request validation by setting validateRequest=false in the Page directive or in the configuration section. However, it is strongly recommended that your application explicitly check all inputs in this case.

Cause:
ASP.Net By default validates all input controls for potentially unsafe contents that can lead to Cross Site Scripting and SQL Injections. Thus it disallows such content by throwing the above Exception. By default it is recommended to allow this check to happen on each postback.

Solution:
To make it working as per above scenario we need to set the ValidateRequest attribute as “false” to disbale the validation request for the page. There is two way to do it as follows.

1. Page level using page directive:
We can disable ValidateRequest by settings the attribute value in page directive.

<%@ Page Language=”C#” AutoEventWireup=”true” ValidateRequest = “false”

or

<pages validateRequest =”false” />

2. Globally using Web.config:
Instead of disabling ValidateRequest page wise we can disable it globally by mentioned the attribute in web.config file.

<system.web>
<page ValidateRequest = “false”/>

<!– Following extra setting require only for .net framework 4.0 or above  –>
<httpRuntime requestValidationMode = “2.0” />
</system.web>

Alternate Solution (Encoding the content):
Unless you actually need users to be able to enter HTML, you must convert the string to its HTML encoding equivalent – basically this means that certain characters (like “<“) are converted to codes (so “<” is converted to “&lt;”, etc). To perform this conversion use HttpUtility.HtmlEncode,

for example:
txtContent.Text = HttpUtility.HtmlEncode(MyTextBox.Text)

Friendly Error Message:
If you want to make the user ensure that the content does not contain dangerous value you can use your own validator.

<asp:RegularExp<b></b>ressionValidator runat=”server” ControlToValidate=”textbox” ValidationExp<b></b>ression=”^[\w]+$” ErrorMessage=”Use only alphanumeric characters” />

Remember:
When disabling the validation request on the page make sure to validate all input from that page.
When disabling the request validation on the application make sure to validate the entire application.

Important
The examples are just to illustrate the given solution, remember to validate as well at the server side.

Share this:
Share

Asp.net: How to Read Application Settings from the Web.config File at Runtime

This example reads an application setting identified by the key customsetting1 from a Web.config file. The appSettings element is a NameValueCollection collection of strings. Working with collection elements can be slightly more complicated than working with other configuration elements.

To obtain configuration settings for the root-level Web configuration, null is passed to the OpenWebConfiguration method.

To update a configuration setting, use the Save or SaveAs method of the configuration object. For more information, see Using the Configuration Classes. For additional code examples, see the AppSettingsSection class and related classes.

This example uses the non-static method of obtaining configuration data, which allows you to pull configuration data from any application. If you are going to obtain configuration information from the application in which your code resides, use the static method, which processes faster. For more information, see the Working with Local and Remote Configuration Settings section in ASP.NET Configuration API Overview.

Example:

C#:
System.Configuration.Configuration rootWebConfig1 = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(null);
if (rootWebConfig1.AppSettings.Settings.Count > 0)
{
System.Configuration.KeyValueConfigurationElement customSetting = rootWebConfig1.AppSettings.Settings[“customsetting1”];

if (customSetting != null)
Console.WriteLine(“customsetting1 application string = \”{0}\””, customSetting.Value);
else
Console.WriteLine(“No customsetting1 application string”);
}

VB.Net:
Dim rootWebConfig1 As System.Configuration.Configuration
rootWebConfig1 = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(Nothing)
If (rootWebConfig1.AppSettings.Settings.Count > 0) Then
Dim customSetting As System.Configuration.KeyValueConfigurationElement
customSetting = rootWebConfig1.AppSettings.Settings(“customsetting1”)
If Not (customSetting.Value = Nothing) Then
Console.WriteLine(“customsetting1 application string = {0}”, customSetting.Value)
Else
Console.WriteLine(“No customsetting1 application string”)
End If
End If

Robust Programming
Values read from the appSettings element of the Web.config file are always of type String. If the specified key does not exist in the Web.config file, no error occurs. Instead, an empty string is returned.

Security
The configuration file should be protected on the server by using Windows security settings to limit who can read the file. Avoid storing sensitive information such as user credentials in the appSettings element of the Web.config file. Also consider encrypting configuration settings.

Share this:
Share

Asp.net Difference between appSettings and Connection Strings in web.config

In previous versions of ASP.NET, connection strings were stored in the appSettings. In ASP.NET 2.0, features, such as Session, Membership, Personalization, and Role Manager, rely on connection strings that are stored in the connectionStrings element. You can also use the connectionStrings element to store connection strings for your own applications.

The difference is that the connectionString section gives you strongly typed access to your connection strings through the ConfigurationManager class. It’s meant for connection strings specifically. The connectionStrings element specifies a collection of database connection strings, as name/value pairs, for ASP.NET applications and features.

A connectionString object is an XML node that has specific attributes to set; and semantically it refers to a database connection string.

Example:
<connectionStrings>
<clear/>
<add name=”LocalSqlServer” connectionString=”Data Source=(local);Initial Catalog=(DBName);Integrated Security=True” providerName=”System.Data.SqlClient” />
</connectionStrings>

You’ll notice it has a few different attributes:

  • name
  • connectionString : This has a specific string inside of it, it needs an Initial Catalog, a security mechanism (in this case Integrated Security
  • providerName

AppSettings is meant to store general settings in web.config is used to store server names, file paths, and other miscellaneous settings needed by an application.. You can use it to store connection strings also, but I recommend not doing that since there is a specific element for it in connectionStrings.

appSettings is just a user-defined Key-value pair that allows you to… well… set application settings.

It can be anything:

Example:
<appSettings>
<add key=”Email” value=”abc@abc.com”/>
<add key=”MasterKey” value=”True”/>
<add key=”GoogleAPI” value=”1234567890-AA”/>
</appSettings>

In many cases, it would just be odd to put the connectionString in a key-value pair like appSettings (semantically and programmatically). As well as it would make it more difficult to encrypt the connectionString when you need to.

Share this:
Share

Asp.Net – what is query string in asp.net with example

Querystring is a kind of variable which can be used to pass a value from one page to another page. hence there are several way to pass value from one page to another page. but we are describing on this article.

Querystring variable pass with variable with “?”

For example: http://www.abc.com/test.html?var1=this is query string variable value.

In the above example “var1” is variable name and “this is query string variable value.” the variable value. we can use this querystring in asp.net as follows.

string var1=Request.QueryString[“var1”];

We can use mutliple querystring variable as well. first variable would use with “?” and other variable will use with “&”

For example: http://www.abc.com/test.html?var1=this is first variable&var2=this is second variable&var3=this is third variable

In the above example “var1”, “var2” and “var3” are querystring variable and we can fetch the values of query string value in asp.net as follows.

string var1=Request.QueryString[“var1”];
string var2=Request.QueryString[“var2”];
string var3=Request.QueryString[“var3”];

Share this:
Share

Dot Net Coding Standard: UI Control Naming Conventions

UI controls would use the following prefixes.  The primary purpose was to make code more readable.

Control Type Prefix
Button btn
CheckBox chk
CheckedListBox lst
ComboBox cmb
ContextMenu mnu
DataGrid dg
DateTimePicker dtp
Form suffix: XXXForm
GroupBox grp
ImageList iml
Label lb
ListBox lst
ListView lvw
Menu mnu
MenuItem mnu
NotificationIcon nfy
Panel pnl
PictureBox pct
ProgressBar prg
RadioButton rad
Splitter spl
StatusBar sts
TabControl tab
TabPage tab
TextBox tb
Timer tmr
TreeView tvw
Share this:
Share