HTMLEncode/HTMLDecode and the apostrophe ASP.net - asp.net

I have text box that allows the user to enter something which is stored in the database, and then another text box which retrieves this value from the database and displays it. Currently, I have something like this:
string text = Server.HTMLDecode(userEnteredText);
//code to put this text into the database
Textbox1.Text = Server.HTMLDecode(textFromDatabase);
The Server.HTMLDecode solves any problems encountered if a user enters the ' char.
However, I noticed if a user enters "&#39" into the textbox, then ASP gives a error again thinking the client is entering potentially dangerous text. Is there anyway around this? I notice on most sites that this is automatically turned into a apostrophe. Any idea how I do this to avoid user input problems?

If you're sure you want this, then set this in your web.config:
<system.web>
<httpRuntime requestValidationMode="2.0" />
<pages validateRequest="false" />
</system.web>

Related

A dangerous Request.Form when value entered into a textbox

I have a simple aspx page through which i am entering Text into a textbox the text are coming though texteditor so the text are with html tags.
Such as <p>My name</p>
the error which i am getting is like:
Server Error '/' Application
A potentially dangerous Request.Form value was detected from the client (ctl00$ctl00$ContentPlaceHolder1$ContentPlaceHolder2$TxtTopicName="<p>kdarftghjh</p>").
What type of error is this and how could i resolve such error.Thanks for any assistance.
If you're using webforms you can add the following to your page-declaration:
validateRequest="false"
You are having html tags in this input(<,>). just remove it or encode it. of if you really need to do like this try adding following part to web.config
<configuration>
<system.web>
<httpRuntime requestValidationMode="2.0" />
</system.web>
<pages validateRequest="false">
</pages>
</configuration>

ASP.NET Page naming using master pages

I have two user types: Readers and Authors. And I'm using Reader.Master and Author.Master for authorization purposes.
Then, there are StoriesR.aspx inherited from Reader.Master and StoriesA.aspx inherited from Author.Master. (In StoriesR.aspx page, you able to read the stories and in StoriesA.aspx you able to write the story.) So,
Reader.Master --> StoriesR.aspx
Author.Master --> StoriesA.aspx
Now, the thing is I don't want my users to see StoriesR.aspx?s=3 or StoriesA.aspx?s=3 in their browsers. I only want them to see stories?s=3. (even without the .aspx part)
How can I achieve this?
you can do this using urlMappings from web.config file
add in web.confing
<system.web>
<!--
Set compilation debug="true" to insert debugging
symbols into the compiled page. Because this
affects performance, set this value to true only
during development.
-->
<urlMappings enabled="true">
<add url="~/reader/stories" mappedUrl="~/reader/StoriesR.aspx"/>
<add url="~/author/stories" mappedUrl="~/author/StoriesA.aspx"/>
This will do url mapping.
You could have one aspx page and change the master page programmatically depending on what type of user they are, Author or Reader.
You can do this in the Page_PreInit event of your aspx page.
Check this c# example or this VB example

Preventing the yellow screen of death

I'm having a problem with asp.net request validation. I have a basic page with a search field and a button. If the user inputs some illegal characters in the search field and clicks the button then of course I can validate his input in JS and everything's OK. However I have also a lot of LinkButtons not associated with the search functionality that do postbacks and when it happens I get the YSOD.
I know you can turn this feature off by adding ValidateRequest="false" in page directives or web.config, however I'd like to know if there is better and more elegant solution than simply disabling request validation completely.
Thanks.
you can use anti XSS Library to avoid cross scripting attack. check for this link AntiXSS asp.net .
and you can turn of the Yellowscreen of Death. by changing the CustomError mode to Remoteonly. so that remote user wont see the YSOD. only local server will see the YSOD
in web.config add line like this.
<configuration>
<system.web>
<customErrors defaultRedirect="yourErrorPage.html"
mode="RemoteOnly">
</customErrors>
</system.web>
</configuration>
Sounds to me like you need to put validation groups against your form elements (could be I'm misunderstanding the question).
(This would be easier if you'd have posted some code)
<asp:Panel runat="server" DefaultButton="btnSearch">
<asp:TextBox runat="server" ID="txtSearch" />
<asp:RequiredFieldValidator runat="server" ControlToValidate="txtSearch" ValidationGroup="vgSearch" ErrorMessage="Search is required!" />
<asp:Button runat="server" ID="btnSearch" ValidationGroup="vgSearch" Text="Search" />
</asp:Panel>
<asp:LinkButton runat="server" ID="btnLogin" Text="Login" ValidationGroup="vgLogin" />
<asp:LinkButton runat="server" ID="btnCakes" Text="Cakes!" ValidationGroup="vgCakes" />
Anyway, the idea is that your search form and associated validators have one validation group, and your other buttons have other validation groups, then the validator won't fire when you click another button.
I'm not actually sure if you NEED the validation groups against individual link buttons, I don't think you do, but I'm putting 'em in there to demonstrate my point.
If I've completely missed the boat, let me know :)
EDIT:
I should mention that I've just thrown the above code together, can't guarantee it's all formatted correctly, etc, etc.
Oddly enough, the day after I attempted to answer this, a co-worked asked me to help with the same problem, so here's what I'm up to so far...
(Bare in mind that while I've been developing in .Net for a number of years, I've never had need to delve that deeply into the page life cycle, ViewState or any of the hideously complicated bits that keep better dev's up at night)
Initially, I thought that overriding the PostBack event in JavaScript would allow me to edit the form post and remove the offending characters, so I tried it with a simple alert, but the potentially dangerous Request.Form was still appearing, so whatever's causing it is happening before the PostBack event is being fired.
So, after investigating the page life cycle, overriding every method I could and doing a whole lot of debugging, I found that the error is being throw in the DeterminePostBackMode method.
Now, by my understanding, this method looks at the form post and converts it to a NameValueCollection, so I built my own NameValueCollection, stripping out the "<" character (I only tested with that character to start with).
Protected Overrides Function DeterminePostBackMode() As System.Collections.Specialized.NameValueCollection
Dim stream As New System.IO.StreamReader(Request.InputStream)
Dim nvCollection As New System.Collections.Specialized.NameValueCollection()
Dim _split() As String = stream.ReadToEnd().Split("&")
If _split.Length > 1 Then
For i As Integer = 0 To _split.Length - 1
Dim kv() As String = _split(i).Split("=")
Dim _key As String = HttpUtility.UrlDecode(kv(0))
Dim _value As String = HttpUtility.UrlDecode(kv(1))
If _value.Contains("<") Then _value = ""
nvCollection.Add(_key, _value)
Next
End If
'For Each s As String In nvCollection
' Response.Write(String.Format("<p>{0}={1}</p>", s, nvCollection(s)))
'Next
Return nvCollection
End Function
And that worked brilliantly, the offending value was being stripped out and the NameValueCollection was being returned without causing an error...
Except I was still seeing the error message.
At the moment, I've tracked it to the PreInit page event, and I'm trying to figure a way around it, I'll update this as I make progress.
UPDATE:
I'm now fairly sure that the issue ISN'T with the values being stored in the ViewState. After reading this excellent article on ViewState, I tried setting the value of a TextBox to "<script" declaratively, which means it shouldn't be stored in the ViewState, which means that the error isn't caused by processing being carried out on the ViewState.
I think.

How to get Correct QueryString Value from URL having UNICODE value in asp.net?

I have a field with nvarchar datatype to store UNICODE value. This field is bound to Repeater Control from which i am redirecting to other page on clicking the link. When this field contains the numeric value in field then, i get the correct QueryString and it displays the Redirected page. But, When it contains some unicode charater(Other than Number or English Character) then it show the value '?????' in QueryString of 'fhn'. How to get this UNICODE QueryString value as it is and display result?
In Repeater ItemTemplate:
<b>घर क्र./House No.</b><%# Eval("HouseNumber")%>
या पत्यावरील
In .cs file:
string HouseNumber = Request.QueryString["fhn"].ToString().Trim();
//here i get the '????' value if it contains unicode value.
Help appreciated!
Try changing it to something more like this:
<!-- Web.Config Configuration File -->``<configuration>
<system.web>
<customErrors mode="Off"/>
<globalization fileEncoding="iso-8859-1" requestEncoding="iso-8859-1"responseEncoding="iso-8859-1"/>
</system.web>
</configuration>
You'll have to be a more precise. You could set request and response encoding in your web.config file:
<system.web>
<globalization requestEncoding="iso-8859-1" responseEncoding="iso-8859-1" />
</system.web>

HTML in an ASP.NET Dynamic Data MultilineText Control

I'm trying to enter a little bit of HTML into an ASP.NET Dynamic Data MultilineText_Edit control, just a couple of <br> tags to have line breaks when I output the value of the column on a web page.
However, when I try to click the "Update" link on the Dynamic Data edit page, nothing happens. I don't even get an error message, which I would expect if HTML input were not allowed via some rule the control has built in. As soon as I remove the tag, the update link works correctly. It's not a column size issue, I can add a bunch more characters to the input and everything works fine.
Is HTML input not allowed in these controls, or is there something else going on? If there is some kind of validation rule, can it be turned off? Or is there something in the database that I need to set? Should I use something other than the default multiline text template?
Input validation is a built in feature in ASP.NET 2.0 or later. I don't know why you are not getting an error, but check this out to see if it helps:
http://www.asp.net/learn/whitepapers/request-validation/
Check these settings, on the page:
<%# Page validateRequest="false" %>
or the web.config:
<configuration>
<system.web>
<pages validateRequest="false" />
</system.web>
</configuration>

Resources