Request Validation - ASP.NET MVC 2 - asp.net-mvc

Has request validation changed for ASP.NET MVC 2, more precisely, not validating?
I did the following:
Web.configs (in App directory and Views directory)
<pages
validateRequest="false"
Controller/Action Attribute
[ValidateInput(false)]
In #Page View Directive
ValidateRequest="false"
The page still gets validated an exception is thrown when HTML content is posted.
UPDATE
Created a new ASP.NET MVC 2 Application and I modified the Home Controller's Index to this
[ValidateInput(false)]
public ActionResult Index(string InputText)
{
ViewData["Message"] = "Welcome to ASP.NET MVC!";
return View();
}
and my View Page
<% using(Html.BeginForm()){ %>
<%= Html.TextBox("InputText") %>
<input type="submit" />
<% } %>
And still the same issue, an exception is thrown.

I should read the error more carefully next time:
To allow pages to override application request validation settings,
set requestValidationMode="2.0" in the configuration section.
After setting this value, you can then disable request validation by
setting validateRequest="false"
I put this in the application's web.config
<system.web>
<httpRuntime requestValidationMode="2.0" requestPathInvalidCharacters="" />
</system.web>
and it worked.
Update:
I was running ASP.NET 4 thats why :P

Insert obligatory warning about XSS here.
That you decorated the controller (or action) with the ValidateInputAttribute should be enough, as all validation is done at this controller level in ASP.NET MVC
I have just tried this now on an action, and it returns a nice, evil alert() when I output it, so I'd venture a guess that there's something else going on here.
Do you have an HandleErrorAttribute set up anywhere?

Related

asp.net mvc User.Identity.Name is empty after posting any page

I have written some simple code to illustrate the problem.
The controller code:
public ActionResult Edit()
{
string un = User.Identity.Name;
return View();
}
[HttpPost]
public ActionResult Edit(int? dummy)
{
string un = User.Identity.Name; // <-- here it's empty string
return View();
}
The Edit.cshtml view code:
#using (Html.BeginForm())
{
#Html.ValidationSummary(true)
<input type="submit" value="Submit" />
}
The User.Identity.Name is not empty after I log in and I go to the Edit page.
But after I submit the Edit page (I make a HTTP POST) the User.Identity.Name becomes empty string and remains empty string no matter what page I access.
In Web.config I have:
<authentication mode="Forms">
<forms loginUrl="~/Account/LogOn" timeout="2880" />
</authentication>
This sounds like a strange problem, and though I can't give you an answer yet, this might help.
FormsAuthentication works by setting a cookie on the browser called .ASPXAUTH. After you sign in, inspect the cookies in your browser and look for it. Also, you can inspect the Request property in the controller action methods to look for that cookie. It will be a weird-looking encoded value. You can also use something like Fiddler2 to make sure that the cookie is being sent when you post the form.
I have run into this problem before, but it had to do with cross-domain requests and machineKey mismatch problems. If both your Edit actions are in the same controller / project / URL / web.config, then perhaps something in the pipeline is removing the cookie, or reconfiguring your User principal during POST requests..? You aren't using OWIN anywhere in the project, right? And there are no global filters other than HandleErrorAttribute?

A potentially dangerous Request.Form value was detected from the client

I am using CKEditor/CKFinder as wysiwyg editor on my MVC.NET site.
I have set [ValidateInput(false)] and it works when debugging it locally, but I receive the following error when I have published the site:
A potentially dangerous Request.Form value was detected from the client (message="<p>
<em>Testing</e...").
can anyone explain why the published site is different from the locally site, especially when I have set [ValidateInput(false)]?
*Update:*I am using .Net 3.5 so shouldn't [ValidateInput(false)] work out the box?
Have you tried setting the htmlEncodeOutput property?
CKEDITOR.replace('editor1', {
htmlEncodeOutput: true });
This should encode the output and you should be able to avoid setting the requestValidationMode.
Documentation for it is here: ckEditor documentation
Add this to your web.config:
<httpRuntime requestValidationMode="2.0" />
Just add an Annotation to the Post method Action as [ValidateInput(false)]
[HttpPost]
[ValidateAntiForgeryToken]
[ValidateInput(false)]
public ActionResult Detail(ModelClass m)
{ return View(); }
ValidateRequest="false"
Add this in the particular Page.
Example:
Add ValidateRequest="false" to your Page:
<%# Page Language="C#" AutoEventWireup="false" Codebehind="MyForm.aspx.cs" Inherits="Proj.MyForm" ValidateRequest="false"%>
Or add to web.config if using .NET Framework 4.0 (Visual Studio 2010)
<httpRuntime requestValidationMode="2.0" />
Use Request.Unvalidated["myTextBox"]
for example,
var text = Request.Unvalidated["myTextBox"];
where "myTextBox" is the form field you want to allow HTML to be posted from.

Does this approach to using ELMaH with MVC smell?

I've been looking around for some approaches to using ELMaH with ASP.Net MVC so that I can use the custom error page for all exceptions including 404s.
There is no shortage of questions asking how to get the /Shared/Error.aspx working correctly in ASP.Net MVC - either with or without ELMaH. I haven't had a problem with that task, but I feel as though my solution to using a custom 404 page alongside ELMaH was too simple and I can't shake the feeling that there should be more to it.
After enabling customErrors in Web.Config, I created a new Action in my HomeController:
public ActionResult PageNotFound()
{
return null;
}
From there I added a new method in my Global.asax file to take advantage of ELMaH's log filtering capabilities and, after letting the exception get logged, redirecting the response back to the aforementioned PageNotFound ActionResult:
public void errorLog_Filtering(object sender, ExceptionFilterEventArgs e)
{
if (e.Exception.GetType().Equals(typeof(HttpException)))
{
HttpException ex = (HttpException)e.Exception;
if (ex.GetHttpCode() == 404)
Response.Redirect("/Home/PageNotFound");
}
}
Am I overlooking something that comes with MVC by default (because I'm still finding my way for a lot of things regarding MVC), or overthinking the problem where a simpler solution exists? Appreciate any input.
I am sure ASP.NET can handle that kind of stuff for you, you don't necessarily have to call anything to redirect to your 404 Action inside your global.asax. See below for an example.
<configuration>
<system.web>
<customErrors mode="On">
<error statusCode="404" redirect="/servererrors/404.aspx" />
</customErrors>
</system.web>
</configuration>
http://www.xefteri.com/articles/show.cfm?id=11

ASP.net MVC [HandleError] not catching exceptions

In two different application, one a custom the other the sample MVC application you get with a new VS2008 MVC project, [HandleError] is not catching exceptions.
In the sample application I have:
[HandleError]
public class HomeController : Controller
{
public ActionResult Index()
{
ViewData["Message"] = "Welcome to ASP.NET MVC!";
throw new Exception();
return View();
}
public ActionResult About()
{
return View();
}
}
which is just the default controller with an exception being thrown for testing.
But it doesn't work. Instead of going to the default error.aspx page it shows the debug information in the browser.
The problem first cropped up in a custom application I'm working on which led me to test it with the sample application. Thinking it had something to do with changes I made in the custom application, I left the sample application completely unchanged with the exception (yuck) of the throw in the index method.
I'm stumped. What am I missing?
In Web.config, change customErrors:
<system.web>
<customErrors mode="On">
</customErrors>
If mode is either Off or RemoteOnly, then you will see the yellow screen of death instead of the custom error page. The reasoning is that developers usually want the more detailed information on the yellow screen of death.
Important: Be careful that your error page itself does not have an error on it!
If it does you'll end up with that ASP.NET custom error page and end up going round in circles and tearing your hair out. Just strip everything out of the page that could possibly cause an error and test it.
Also with respect to 'customErrors' being ON or OFF there are several contributing factors to whether or not the friendly error page (your Errors.aspx) page will be shown or not.
See this blog (except below)
HttpContext.IsCustomErrorEnabled - looks at three different sources
The web.config's <deployment> section's retail property. This is a
useful property to set when deploying
your application to a production
server. This overrides any other
settings for custom errors.
The web.config's <customErrors> section's mode property. This setting
indicates whether custom errors are
enabled at all, and if so whether they
are enabled only for remote requests.
The HttpRequest object's IsLocal property. If custom errors are enabled
only for remote requests, you need to
know whether the request is from a
remote computer.
The idea here is that you can have 'customErrors' turned OFF during development - when you do want to see the errors, and then enable it for production only.
This MSDN article discusses the attribute further.
Another reason for this problem may be ,
In Template MVC Application (generated by VS2008 / VS2008 Express) , Error.aspx (generated by VS) uses Master Page.
If Master Page access any ViewData it will throw null reference Exception , then the error.aspx won't be shown.
Use this Simple code as your Error.aspx , it will solve the problem, (along with CustomErrors=On )
<%# Page Language="C#" Inherits="System.Web.Mvc.ViewPage<System.Web.Mvc.HandleErrorInfo>" %>
<%= Model.Exception.Message %>
I have struggled with this as well and I believe I understand the problem now.
In short the requirements for having [HandleError] work as expected are:
You must enable custom errors in web.config AND you must also specify where your error view is in the <customErrors> tag.
Example:
<customErrors mode="On" defaultRedirect="Error" />
Leaving off the defaultRedirect="Error" part will instead yield a 500 error in the browser--NOT the ASP.NET error page (YSOD).
Also you do not have to be in Release mode. I tested this with a Debug build and it worked fine.
My environment was Visual Studio 2010 using .NET 4 and the standard, "ASP.NET MVC 2 Web Application" project template.
What confused me was the MSDN documentation for the HandleErrorAttribute Class. It doesn't explicitly say you must turn on custom errors in web.config. And I assumed all I needed was the [Handle Error] attribute.
There is some silly situation which once happened with me, so might be helpfull for someone.
Be sure that you've added <customErrors mode="On" /> to the correct web.config file.
Sometimes (especially, when you work with something like Resharper, and open your files with typing their name, but not via Solution Explorer), you can simply open a web.config either from Views folder or even from another project.
Watch out: in my case I was trying to get the HandleError attribute to catch an exception thrown inside the Controllers constructor! Of course it won't catch it. The HandleError attribute only catches exceptions thrown inside Controller actions. It's right there in the MSDN page (should've paid more attention to that):
Represents an attribute that is used to handle an exception that is
thrown by an action method.
Another thing that was happening is that the Controller's OnException(ExceptionContext exceptionContext) overridden method was never being called. Again: of course it would not be called since I was throwing an exception inside the Controller's constructor.
I spent 1 hour trying to figure this out. :o) Hope it helps the next soul...
As a hint: remember that the HandleError attribute only catches 500 errors. For the other ones you should declare the <customErrors> section in Web.config:
<customErrors mode="On">
<error statusCode="403" redirect="~/403" />
<error statusCode="404" redirect="~/404" />
</customErrors>

trying to submit rich text editor content in asp.net mvc and getting "potentially dangerous Request.Form value was detected"

I am using TinyMCE in asp.net mvc and getting the error message "a potentially dangerous Request.Form value was detected" when trying to save the text from the TinyMCE editor.
I set ValidateRequest="false" both in web.config and on the page. Any ideas?
Just add the ValidateInput attribute to your action and set it to false.
Like this.
[ValidateInput(false)]
public ActionResult Submit(string FormContent)
{
}
To get this working in ASP.NET MVC 2.0, I also had to add
<httpRuntime requestValidationMode="2.0" />
to the
<system.web>
section of my web.config file

Resources