MVC :: Handle HttpRequestValidationException Without Turning Off ValidateInput?
Mar 18, 2011
Is there a way I can handle HttpRequestValidationException without turning off ValidateInput?
What I really want is all HTML posted from a form to be automatically encoded in the model unless a particular property has the AllowHtml attribute set.
If I have to turn off ValidateInput, then what happens to the rest of my model validation? Will it still be validated or do I need to explicitally check ModelState.IsValid?
I'm also catching the exception in a custom model binder class but every time I try to access the offending property from Request.Form, the exception gets thrown. Is there a way to get that value in the model binder?
I want to store certain html tags in my database to the layout of content, for example <h3> and <p> tags. The problem is with ValidateInput set to True, you get "Potential Danger error" when you try sending content with html tags.
With it set to False, you open yourself to all sorts of potential dangers. So Here is what I'm wanting to achieve:
I hope you like the image ! lol I spent 10 minutes in Photoshop to create it.
So eventhing that goes in, I want as encoded, but when I get content back, I want to decode only the <h3> and <p> tags. ! What do you think of my solution ? Bad, Good ?
I have a website which sometimes collects data from users via text boxes, and stores the data for later display.The .aspx site uses standard out-of-the-box asp.net Request Validation to stop cross-site scripting attacks.I now want to give certain users the option of populating the data via a web service rather than a web page.So I am creating an .asmx web service.1)Am I correct in thinking that in .net 3.5, data coming in to a .asmx web service is completely unprotected off-the-shelf from cross-site scripting attacks, and has to be treated with caution and html-encoded and inspected
Like many others, my web site now throws the following exception under .NET 4.0 where it used to behave perfectly well under .NET 2.0:
A potentially dangerous Request.Form value was detected from the client.I have added the following element to my web.config file:
<httpRuntime requestValidationMode="2.0" />
However, the error still appears. It is caused by the log-in and log-out buttons on my site, which are contained in a master-page. I think the reason might be because I make extensive use of hidden fields in my web pages, which the ASP.NET validation now complains about when the pages are posted back to the server after the buttons are pressed:
A potentially dangerous Request.Form value was detected from the client (ctl00$ctl00$mainContent_PH$mainContent_lCol_PH$hdnPageContent="...ssociation's Executive Com...").
(ctl00$ctl00$mainContent_PH$mainContent_lCol_PH$hdnPageContent is a hidden field containing large amounts of HTML.) The merits of this design are probably debatable; however, what I need now is a way of letting these buttons work whilst retaining some validation for the rest of the site (as I have always had up until now).
I have this piece of code to handle the HttpRequestValidationException in my global.asax.cs file.protected void Application_Error(object sender, EventArgs e)
I think I might have stumbled onto a bug in ASP.NET MVC 3 RC. When I setup my MVC2 project in a new MVC3 project, copy paste classes, code, change name spaces, etc, etc, I ran into an issue in the following, simplified for explanation purpose, scenario:
Model:
public class WineDetails { [SkipRequestValidation] [Required(ErrorMessage = "Beschrijving verplicht")] public string Description { get; set; } }
ViewModel:
public class ViewModelCreateWine { public MasterData MasterData { get; set; } public WineDetails WineDetails { get; set; } }
ActionMethod:
[AcceptVerbs(HttpVerbs.Post)] public ActionResult CreateWine(ViewModelCreateWine viewModelCreateWine) { GetMasterDataRegions(viewModelCreateWine); if (Request.Params.ToString().IndexOf("Save") > 0) { if (TryValidateModel(viewModelCreateWine.WineDetails)) { m_wineService.CreateWine(viewModelCreateWine.WineDetails); return RedirectToAction("index", "Admin"); } } return View(viewModelCreateWine); }
The ActionMethod "CreateWine" needs to call the "CreateWine" method in the WineService so that in the end a new Wine is added to the Database. So far it looks ok. As shown in the above code the [SkipRequestValidation] is set on the "Description" property of the WineDetails model so that the user can add Rich Text to the description and HTML elements are allowed during the Request validation. This works perfectly fine until the Params collection of the Request is accessed in the code to check if the Save button is clicked. When this line of code is trying to execute the following exception is thrown:
Exception Details: System.Web.HttpRequestValidationException: A potentially dangerous Request.Form value was detected from the client (ViewModelCreateWine.WineDetails.Description="<p>HTML Content with...").
The same exception is thrown when I put the [ValidateInput(false)] attribute on the action method. When I comment out the "if" statement and its content there is no issue and the model validation works just fine and skips the Request Validation on the Description property as expected.
In MVC2 the above code worked fine with the [ValidateInput(false)] attribute on the action method.As I said I'm not sure if this is a bug, it very well might be my own stupidity, but I thought it would be worth to mention here. So any feedback is more than welcome.
this exception is caused by entering scripts or disallowed text as "<script>", "<h1>" by the user. This exception will be thrown while processing the request.
After searching and trying, most of the solutions were to:
1- disable request validation in the page header (validateRequest="false") or in the pages section in web.config.
I dont see this is a solution, the XSS problem is still there, it just does not throw the exception.
2- To encode the text and decode it using Server.HtmlEncode and Server.HtmlDecode.
This is a good one, but have to go every single textbox and call this method (Server.Encode(txtAddress.Text)), but this require alot of effort to change the whole site, and some of them may be forgotten.
I was thinking of creating a new TextBox control (MyTextBox) to inherit from System.Web.UI.WebControls.TextBox and override the Text property, then Encode base.Text in the get accessor, and Decode base.Text in the set accessor.
This will also require to change the whole site, to use MyTextBox instead of TextBox.
In the load event of a web user control I have the following code which I am using to call a function in order to populate a HTML Text Area.The page hosting the control loads fine the first time it loads but on postback it throws the error
Quote:System.Web.HttpRequestValidationException: A potentially dangerous Request.Form value was detected from the client I have seen people suggest <%@ Page ... validateRequest="false" %>
Firstly I would like to handle this at control level rather than on the hosting page .
Code: if (!Page.ClientScript.IsStartupScriptRegistered("AddText")) { Page.ClientScript.RegisterStartupScript [code]....
I think I know the answer to this, just want to make sure.
Question: there's no way to turn off a timer in ASP.NET on the client side (easily—I've seen the undocumented hacks on the net). Therefore, you have to set up you own logic client side while the timer is running server side, correct?
I went through these examples and understand them:
So, the pseudocode for a trigger done programically—so you do something when somebody clicks a button Button1 would be-- after you set up a ScriptManager, UpdatePanel and suitable ASync PostBack triggers in XAML (as per the above links) so that the Ticks event is triggered in the UpdatePanel:
public partial class MyWebForm : System.Web.UI.Page
{ bool myTriggeringBoolean; //used to turn off and on code in the Timer's Tick event [code]....
I'm sort of new to ASP.NET. What i've done here is create a list of Newsletters seperated by University newsletters, and Alpha Newsletters. What I have now been asked to do is make these 2 lists into 1 list. I can't figure a Way to do it without designing the database? Does anyone have any ideas? Take these 2 lists and make 1? Using odsNewsletterAlpha and odsNewsletterUni to create 1 list?
I have bunch of HTML code I am using to make rounded edge boxes on my controls. Is there a way to take this code and turn it into some kind of control or something so I do not have to keep pasting 10 lines of HTML code around everything I do?
One additional thing to note, the number HTML tags used inside the inner most DIV will change depending on where I use it in my site. So in some cases I will only have 1 tag and 1 tag but in other cases I could have 1 tag, 1 tag, 3 tags, and a HTML table. How can I make that work?
I created a little web service to minify JavaScript, and everything was nice, with all my tests passing. Then I noticed a bug: if I tried to minify alert('<script>');, it would throw a HttpRequestValidationException.
So that's easy enough to fix. I'll just add [AllowHtml] to my controller. But what would be a good way to unit test that this doesn't happen in the future?
The following was my first thought:
[TestMethod] public void Minify_DoesntChokeOnHtml() { try { using (var controller = ServiceLocator.Current.GetInstance<MinifyController>()) { return controller.Minify("alert('<script></script>');"); } } catch (HttpRequestValidationException) { Assert.Fail("Request validation prevented HTML from existing inside the JavaScript."); } }
However, this doesn't work since I am just getting a controller instance and running methods on it, instead of firing up the whole ASP.NET pipeline.
What would be a good unit test for this? Maybe reflector on the controller method to see if the [AllowHtml] attribute is present? That seems very structural, and unlikely to survive a refactoring; something functional might make more sense.
One thing I really love about web browsers, is the autocomplete feature they have for different controls, like textboxes in forms. However, some times users get confused with the dropdown appearing. So, we would like to be able to disable the autocomplete feature for some textboxes on some of our ASP.NET WebForms pages. Isn't there a property which controls that? Or is that done through JavaScript?
I have an application where I don't want the browser to be able to remember passwords. I can see the AutoCompleteType = disable and that seems to work in IE, but I also need to support FireFox. Setting autocomplete="off" doesn't seem to do anything. Is there anyway for me to kill the autocomplete of a password text box in FireFox?
I'm wondering if it's possible to be able to use an HTML editor (such as TinyMCE) in an ASP.NET form without turning off validation for the entire page. There are other fields in the page that I want to use validation for. Will those not get validated with validation controls if you set ValidateRequest="false" in the page directive?
I ran into a strange issue with the AJAX MaskedEditExtender control, the extender is used with the Mask="99/99/9999" and MaskType="Date". Initially when the page loads the textbox was set to readonly using textbox.Attributes.Add("readonly", "readonly") in the codebehind. After the page loads if the user clicks on a certain button it would change the textbox to editable using javascript code: textbox.readOnly = false. The strange thing is after that if you start typing in the textbox you can see the entire mask (__/__/____) shifting to the right as you type. For example it looks something like this: 09__/__/____ instead of the normal 09/__/____.
If the textbox was never set to readonly in the first place this behavior won't happen. So it seems something got messed up when changing from readonly to not. I was able to reproduce this in a barebone aspx page with just the textbox, the mask extender, and a button that when clicked turning off the textbox's readonly. Anyone knows how I can fix this?
I have a listview whit "select" button.... i want when i click this button the listview should show a Delete buttonn What is wrong in my code ..i press select button there is noting hapning??
In the repeater, there are a number of dropdownlist controls. Each one is hooked up to an event which triggers when changed. When one instance is changed I would like to disable all other instances of the DDL control.