Form Post Error - asp.net

Can anyone explain what might be causing this error. Im thinking its the quotes.
Exception Details: System.Web.HttpRequestValidationException: A potentially
dangerousRequest.Form value was detected from the client
(ctl00$ContentPlaceHolder1$DetailsView1$txtContent="...l economy.<br /><br />The
Prop...").

The contents of a control (probably a textbox) contains what ASP.net considers to be markup, eg:
<br /><br />
You can add ValidateRequest="false" to the Page directive in your .aspx file as follows:
<%# Page ........ ValidateRequest="false" ........ %>
As other answers noted, asp.net is doing this to try and protect you from potentially malicious input so make sure you're aware of the risk and encode/decode user data appropriately.

I think you can take a look at this A potentially dangerous Request.Form value was detected

Its the html "<br/>" tags.
Here's an article with a brief explanation . Also shows you how to work around it by turning off validation. Though I guess that would be a bit dangerous to just turn it off.

It actually should be
<br /><br />
it complains about.

That would be the '<' and '>'.
EDIT: It's assumed that including html entries in form responses is intended as an attack on the server on which the form resides. So, by default, any code that resembles html (i.e. includes '<' or '>') is automatically flagged as a problem.
One way to resolve this is to turn off this type of validation by setting validateRequest="false" in the Page directive for that page, but there are other (and better) ways to work around that.
Here's some information from Microsoft about this issue.

My idea: allow this exception to be thrown. Use Application_Error handler to write code, that redirects (using Response.Redirect - this is important, since this gives users’ browser ability to go back) user to a custom error page. On this page write some text explaining that users had incorrectly input some text. Something like:
"Dear user, you have entered some invalid text, like “<” or “.”. Please, enter text using only characters and numbers".
Put a link on that page, and this link can contain a javascript "back" command:
href="javascript: history.go(-1)"
Users after clicking suchlink will be redirected by their browsers to the previous page, where they can re-edit their input.

Related

Is this asp compiled somehow?

I have an aspx document (I know nothing about asp, .net, aspx, nada). It is a normal html table structure for the most part, but there are strings of asp that seem to be inserting some sort of dynamic content. They are in the form:
<asp:Image ID="imgTopImage" runat="server" ImageUrl="~/Images/topbar.jpg" />
<asp:Label ID="lblStyleCaption" runat="server" CssClass="label_caption" Text="Theme: " Visible="false" />
<asp:DropDownList ID="dropStyles" Width="150" runat="server" AutoPostBack="true" />
It seems that whenever I delete one of these——something as innocuous as, say, the line with the asp:Image tag, which I would think should just remove the image, when I load the page I get run-time errors. It's very particular. My question is, is this compiled somehow, which is making it so fragile. Even just changing the topbar.jpg to something.png gives me an error. Do I need to track down the original files this was compiled from, or is this normal server-side asp(x?) that I'm just somehow else goofing up my changes to?
ASPX pages are compiled, and those tags refer to objects that are known to the server, so removing them could cause errors.
First, some basics in layman's terms
Tags that begin with ASP: (Example, <ASP:Button id="btnSubmit" runat="Server" Text="Click Me" />)
are not standard html buttons. They are server controls. When generating the html that goes out to the browser, the ASP.NET runtime looks at the server controls and creates the appropriate content depending on the browser visiting the page.
In the case of the Button control, it's usually a standard html button, but the runtime also generates the JavaScript and such to handle the button's server-side click event.
Why you're probably seeing errors when you remove a control:
Quite often, there's server-side code that's written that accesses these controls. For example, the developer may have decided to change the Text or the Visible property due to some event.
If this is the case, and you remove the <asp:Button> tag, then there will be server-side code that references an object that no longer exists in the aspx page, hence the errors.
More at these links on Server Controls:
http://www.w3schools.com/aspnet/aspnet_controls.asp
(Actually, this older one is better for a new-to-asp.net developer: http://msdn.microsoft.com/en-us/library/zsyt68f1(VS.71).aspx
http://support.microsoft.com/kb/306459
I'd also recommend taking some time watching basic videos or going through the tutorials at http://www.asp.net/get-started
I just noticed this in your question:
Even just changing the topbar.jpg to something.png gives me an error.
That is a bit odd, but I know of at least one way it could happen...
Generally, Visual Studio will give you a warning (and not an error) if you include a relative URL to an image or a linked page that doesn't exist. The warning shouldn't block you from compiling. However, Visual Studio does have a setting that tells it to treat warnings as errors. That will block it from compiling. Here's how that would be set up:
from Project Settings> Configuration Properties select the build
setting and change the “treat warnings as errors” settings to true.
If you wish to NOT treat warnings as errors, simply change the setting to false.

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.

Can I place a comment inside a tag in ASP.NET?

I am looking to display this in my .aspx page, without using special character XML tags, can this be achieved?
<asp:ServerTag Property1="a"
Property2="b"
Property3="c" <%-- Comment why this particular property is necessary --%>
Property4="d" />
However, I am greeted with the error message Server tags cannot contain <% ... %> constructs. If I use an HTML <!-- --> tag, I'm told the server tag is not well formed.
Is there any other syntax to make this possible?
Put server-side comment above your server-side control.
<!-- client-side comment (html) - appears in html source but not rendered on page
<%-- server-side comment - stripped out on server, never sees light of day, browser never knows about it
like this
<%-- Usage:
Property2 is xyz...
Property3 will .. abc. Ignore Property 1 when this is set. etc
--%>
<asp:ServerTag Property1="a"
Property2="b"
Property3="c"
Property4="d" />
It's just like putting source code comments above your functions.
Think "server to server". It will make the difference between your HTML source looking like
cluttered with "pass through" html comment <!--:
<!-- Property usage: abc, def, ...xyz -->
Rendered server control contents.
vs. the cleaner stripped out " <%-- source:
Rendered server control contents.
Less bandwidth with latter too. No extraneous (and confusing to user) comments in HTML source.
It's not possible, no. The server tags need to be well-formed XML and you can't have tags like that in XML. You can put a comment at the top, of course, like so:
<!-- Property2 needed because... -->
<asp:ServerTag Property1="a" Property2="b" Property3="c" />
Not necessarily like that but you may want to consider decorating the property in c# to let the user know its relevance. After that something like resharper (or maybe vs) will give you this information when you try to set it.

How do i get rid of __o is not declared?

I have some code in my master page that sets up a a hyperlink with some context sensitive information
<%If Not IsNothing(Profile.ClientID) Then%>
<span class="menu-nav">
<a target="_blank"
href=
"http://b/x.aspx?ClientID=<%=Profile.ClientID.ToString()%>&Initials=<%=Session("Initials")%>"
>
Send
<br />
SMS
<br />
</a>
</span>
<%End If %>
<span class="menu-nav"> <!-- Name __o is not declared Error is flagged here-->
Now the issue seems to be in the href part. If I remove the dynamic code the error disappears. Can anyone tell me how to resolve this issue?
I've found the answer on the .net forums. It contains a good explanation of why ASP.Net is acting the way it is:
We have finally obtained reliable repro and identified the underlying issue. A trivial repro looks like this:
<% if (true) { %>
<%=1%>
<% } %>
<%=2%>
In order to provide intellisense in <%= %> blocks at design time, ASP.NET generates assignment to a temporary __o variable and language (VB or C#) then provide the intellisense for the variable. That is done when page compiler sees the first <%= ... %> block. But here, the block is inside the if, so after the if closes, the variable goes out of scope. We end up generating something like this:
if (true) {
object #__o;
#__o = 1;
}
#__o = 2;
The workaround is to add a dummy expression early in the page. E.g. <%="" %>. This will not render anything, and it will make sure that __o is declared top level in the Render method, before any potential ‘if’ (or other scoping) statement.
An alternative solution is to simply use
<% response.write(var) %>
instead of
<%= var %>
Yes, I have experienced the same bug occasionally in pages that use server side constructs on ASPX pages.
Overtime, I found a fix for it (I'm sorry, I just haven't been able to find out where I found this bit of info again.) and that fix is to put the following code above the errant <%...%> block:
<%-- For other devs: Do not remove below line. --%>
<%="" %>
<%-- For other devs: Do not remove above line. --%>
Apparently, where you put the above code makes all the difference to VS.NET, so it may take a few tries to get it right.
This is an odd solution, but for me I managed to fix this problem by simply closing the offending open files in Visual Studio.
With them open, i was erratically getting the __o problem.
As soon as I closed them, the __o problem disappeared.
After some hours of googling and analyzing bunch of aspx'ses in my current project seems I've found the solution, that is working for me. Would to advise strongly avoid html-style comments:
<!-- ... -->
inside aspx page. Instead of it use aspx-style comments
<%-- ... --%>
Additionally it helped me obtain that vs intellisense and code highlighting became working again and the mainly thing - this case had begun from it - vs can now hit the breakpoints inside embedded pieces of vb/cs code! And no any damn "This is not a valid location for a breakpoint" message.
When I've cleaned the solution, restarted IIS and it is still mysteriously playing up, I find this can sometimes be caused by pasting an ASPX source file's contents from another system into Visual Studio which "helpfully" updates the code, possibly changing some IDs and breaking the page.
Pasting it into another editor (Notepad++?) then saving it stops Visual Studio from "being helpful" and the page works again.

Form Elements in ASP.NET Master Pages and Content Pages

OK, another road bump in my current project.
I have never had form elements in both my master and content pages, I tend to have all the forms in the content where relevant.
In the current project however, we have a page where they want both. A login form at the top right, and a questions form in the content.
Having tried to get this in, I have run in to the issue of ASP.NET moaning about the need for a single form element in a master page. TBH, I really dont get why this is a requirement on ASP.NET's part, but hey ho.
Does anyone know if/how I can get the master and content pages to contain form elements that work independantly?
If not, can you offer advice on how to proceed to get the desired look/functionality?
Thought I would review some of my outstanding questions and see if I can close some of them off.
This one was an interesting one. I outright refused to believe you can only have one form on an ASP.NET page. This to me made no sense. I have seen plenty of webpages that have more than one form on a web page, why should an ASP.NET page be any different?
So, it got me thinking.
Why does a ASP.NET page need a form element?
ASP.NET pages try to emulate the WinForms environment, by provided state persistance through the PostBack model. This provides an element of state to a stateless environment. In order to do this, the runtime needs to be able to have the ability to maintain this state within each "form". It does this by posting back data to itself. It's important to note that:
There is nothing really fancy about a PostBack.
It uses a HTTP form and POST, the same as any other form, from any other stack.
Just because it looks like it might be doing something special, its not, all that happens is it POST's back with some info about what caused it, so you can do things like handle client-side events, in server-side code.
So why only one?
This to me was the million pound question (I am British). I understand that ASP.NET needs this, especially if you are using ASP.NET server controls, but why the hell can't I make my own additional forms?
So, I thought screw it, just make your own form!
And I did. I added a bog-standard, simple form with a submit action of "#". This then performs a POST to the current page, with the Form data for the given form in the request.
Guess what? It all worked fine. So I ended up with:
A master page, with a HTML form in
This form posts back to the current page (basically the page using the master).
In the Page_Load code-behind for the master, I then added code to check the request to see what data was passed in the request. If it contains data (say a hidden field) then I know the post was sourced from the Form on the master page, if not, then it is most liekly a PostBack from content, and can be ignored.
I then surrounded the Content tags with <form runat="server" id="aspNetForm"...> </form> tags. This meant that all content pages automatically had a form to work with.
This provided me with a relatively simple, clean solution to my problem. My login form works fine in tandem with all the content forms created, some of which are complex forms, others use lots of server controls and many PostBacks, and so on.
I hope this helps others.
the form tag itself is in the MasterPage, as such, you can code any asp.net server controls onto the master page that you wish. And you can write up the processing logic for those server controls on the master page's code behind file.
So, in your example, you can have the login controls on the upper right of the master page, and then have the authentication logic in the code page for the MASTER PAGE, not your content page.
This allows you to have the login controls on every page, and maintain that processing, as well as maintain the content controls and their processing on their individual pages.
Everyone else has already mentioned that you can only have a single form element in a given ASP.NET page, and that it would be contained in the master page. So far, so good. But I don't think that helps you get fully where you want to be ...
In your master pages, you've (I assume!) defined asp:ContentPlaceHolder controls. Your pages which use the master then have corresponding asp:Content tags. All your page content must go in these corresponding asp:Content tags.
Once in that tag, they are part of the master page's form. The master page can respond to events from its own controls, and the pages themselves respond to events from their own controls, and you're set.
If you need the page to interact with the master page, you can access it via the Page.Master property. To interact with any publicly-visible code (methods, properties, etc.) from the master page, you'd cast this property to the correct type, and access the publicly-visible code from there.
That should get you where you need to be in this scenario. (It's worked for me on multiple sites!)
Rob,
Interesting solution. I don't see any problem with what you are doing. The problem some may encounter however, is if they try to do this with 2 server forms. There's no rule in ASP.NET that you can't have more than 1 HTML form on a page, just that you can't have more than one "runat='server'" form on the page. Obviously you've found a pretty easy way of meeting your needs.
I've found that for the most part dealing with a single form is not a problem because the ASP.NET framework basically separates everything for us with naming containers. But in your initial post comment you hit on the important factor that was absent yet critical to the essence of the original question: enter key behavior. That always throws a monkey wrench into the works.
If you were to use a standard "all encompassing" server form, couldn't you capture the right action using a textbox text changed event? Of course, if the user changed both values before hitting enter on either you would get strange behavior. And I think the core problem with the enter key is that once you have more than one submit input on an HTML form, hitting ENTER in a textbox doesn't do anything. Only when there is a single INPUT element does the enter key cause one to be "clicked".
None of the previous answers gave a code example. Here's a simplified version of the Visual Studio 2012 Site.Master that illustrates how to do this:
<%# Master Language="C#" AutoEventWireup="true" CodeBehind="Site - Copy.Master.cs" Inherits="WebApplication1.Site1Master" %>
<!DOCTYPE html>
<html>
<head runat="server">
<title>This is a title</title>
<asp:ContentPlaceHolder runat="server" ID="HeadContent" />
</head>
<body>
<form runat="server">
<header>
<div class="content-wrapper">
<div class="float-right">
<section id="login">
<asp:LoginView runat="server" ViewStateMode="Disabled">
<AnonymousTemplate>
<asp:ContentPlaceHolder runat="server" ID="AnonContent" />
</AnonymousTemplate>
<LoggedInTemplate>
<asp:ContentPlaceHolder runat="server" ID="LoggedInContent" />
</LoggedInTemplate>
</asp:LoginView>
</section>
</div>
</div>
</header>
<div id="body">
<asp:ContentPlaceHolder runat="server" ID="FeaturedContent" />
<section class="content-wrapper main-content clear-fix">
<asp:ContentPlaceHolder runat="server" ID="MainContent" />
</section>
</div>
</form>
</body>
</html>
So you have everything wrapped by a single Form element, so you can place controls in the master page, yet your content pages can also use controls.
You can only have one form on an ASP.NET page. One way to handle this is to put an event handler on the login button in the master page. The handler will validate the user and redirect to the same page on success (to correctly run the Page_Load handler, which is run before event handlers).
I solved the "clicking the return key in the login sub-form causes the main form to submit" problem in my current project by embedding an iframe into the master page. The iframe pointed to the login.aspx page which authenticated the user.
<iframe id="login" src="login.aspx" frameborder="0" enableviewstate="false" scrolling="no" runat="server"></iframe>
(form some reason I needed the closing /iframe tag otherwise design view got confused)
You can access MasterPage controls from the aspx form by:
add the detractive tag to the aspx form <%# MasterType VirtualPath="~/Site.Master %>
and in the code behind use Master.FindControl(); to get the control by ID
for Example if you want to get the
Control form = Master.FindControl("form")
now you can use the master page's form in your code.
I hope this help.
Salve! In a similar thread, I posted an answer that might help you. You can use jquery to add content to an empty div. That content can include form tags, and even a submit function independant of anything the server-side code is doing. The only downside to this is if the user does not have javascript enabled!
Instead of reposting the same answer (and the code too), here is the link:
Jquery Ajax loading form on asp.net webform
This is a limitation of ASP.NET
ASP.NET is designed to have one form per page and only one form. When it was originally designed that was not a problem.
However since then this has been identified as a huge problem with accessibility.
Microsoft Fix for this was ASP.NET MVC, if you are able to I would suggest considering moving to ASP.NET MVC as it solves a large number of problems with ASP.NET
You can have more than 1 form. (just only 1 visiable at a time) codeline 1 = form 1 visable / form 2 hidden . Code 2 Form 2 visable / form 1 hidden. = solved (this is great for static contact forms as well
no, you can only have one asp.net form per page.
That has been the rule since 1.0
They should both share the same form

Resources