“A potentially dangerous Request.Form value was detected from the client” - asp.net-mvc

How do I disable this page validation entirely and for good in ASP.NET MVC 3?
I have looked through the error message and the other questions with the same title. None of the suggested solutions help:
I do have a
<httpRuntime requestValidationMode="2.0" />
in the <system.web> section in Web.config.
I also do have a validateRequest="false" attribute on the <pages>...</pages> element.
But I am still getting the error. What else can I try?

Add the following line of code:
GlobalFilters.Filters.Add(new ValidateInputAttribute(false));
to the Application_Start() method.

Add [AllowHtml] to the action, parameter, or property.
EDIT: If you want to allow it anywhere, add new ValidateInputAttribute(false)] to GlobalFilters.Filters.

Related

Can I change the FormsAuthentication cookie name in asp.net dynamically?

I want to set FormsAuthentication cookie name dynammically, for example a guid. how can i do that. I can already change it to whatever I want in web.config. I just can't do it in code and dynamically.Please help.
<authentication mode="Forms">
<forms name="myName" loginUrl="~/Account/Login" defaultUrl="~/Admin/admin" cookieless="UseCookies" slidingExpiration="true" timeout="40320"/>
</authentication>
The reason that I want to do this is, i have several instances of my application on the same host and i do not want them to overwrite each other's cookies.
I have been struggling with Cookies with quite a few days. It has been an awesome learning experience.
So wanted to share the possible ways I found & discovered: There are several HACKs to modify Forms Authentication Cookie name:
You can automate the modification of cookie name under Authenticaiton secion of Web.Config file in Application_Start event in Global.asax. Thanks to Ron for sharing this. But I could not guarantee that the user whose identity would be used to run application domain have enough privileges to modify the file on disk or not. Hence I needed an improvised solution, so I devised following.
Thanks to ILSpy for letting me see inside the FormsAuthentication class, and many thanks to Reflection to let me modify the private field of a class. I used following code to modify the cookie name on run-time with following small piece of code and this worked like a charm !!!
protected void Application_Start(Object sender, EventArgs e)
{
// This will enforce that FormsAuthentication class is loaded from configuration settings for the application.
FormsAuthentication.Initialize();
// The new cookie name whatever you need can go here, I needed some value from my application setting to be prefixed so I used it.
string newCookieName = string.Format("{0}.ASPXAUTH", ConfigurationManager.AppSettings["SomeSettingThatIsUniquetoSite"]);
// Modifying underlying baking field that points to FormsAuthentication.FormsCookieName
Type type = typeof(FormsAuthentication);
System.Reflection.FieldInfo field = type.GetField("_FormsName", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static);
field.SetValue(null, newCookieName);
}
Suggestions, loopholes are requested as this is my first answer on this forum.
You can't do this in code; the property FormsAuthentication.FormsCookieName is readonly. I would use the following configuration in web.config:
<authentication mode="Forms">
<forms configSource="forms.config" />
</authentication>
Then give each instance of the application its own forms.config:
<forms name="CookieNameForThisInstance" />

Where to put 'Replace' code?

I am developing MVC application and am testing it now.
I am trying to insert <test> in the Database for address field. As it contains anguler brackets it's giving an error. For that I use the below code in controller.
[HttpPost]
public ActionResult Create(Employee employee)
{
if (ModelState.IsValid)
{
employee.Address.Replace("<", "<").Replace(">", ">");
db.Employees.Add(employee);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.ReportsToId = new SelectList(db.Employees, "Id", "FirstName", employee.ReportsToId);
return View(employee);
}
But cursor didn't come to this code. Where to write replace code?
Before cursor comes to that code, it's giving an error:
A potentially dangerous Request.Form value was detected from the client
(Address ="<test>").
Read this answer for similar question.
Conclusion: Use the [AllowHtml] attribute over the Address property or change the web.config to use requestValidationMode 2.0:
<configuration>
<system.web>
<httpRuntime requestValidationMode="2.0" />
</system.web>
<pages validateRequest="false">
</pages>
</configuration>
Change employee.Address.Replace("<", "<").Replace(">", ">"); to employee.Address = employee.Address.Replace("<", "<").Replace(">", ">");
This way it is taking the employee.Address string and replacing the < and > symbols then saving the string back to employee.Address.
Also it may need to be before the if (ModelState.IsValid) part.
There are two problems in your code that you have to solve.
First, as you pointed out, the error:
A potentially dangerous Request.Form value was detected from the client (Address ="<test>").
This error happens because, for the sake of security, MVC does not allow such string (your is like some html element) to be sent to your action method by default. That is to prevent the user submit some dangerous input to attach your site. For example, rather than , you could type alert('hahaha'), and if you does not encode that input, everyone access the page that contains this address field will get an alert box. And that is why you cannot get to the "Replace code" when debugging, the whole method just won't run because of this error.
That said, there are many options to solve this first error, but you can simply add a ValidateInput attribute to your action method.
[HttpPost]
[ValidateInput(false)]
public ActionResult Create(Employee employee)
By doing this, you are telling MVC to trust you that you will encode that dangerous input at some point. And you are doing that by the Replace code. That is pretty fine. But if you are just using #yourTable.Address to render the data in some view, you don't need to bother Replacing < and > in your action code. MVC Razor engine would do the encoding for you when you are rendering the data through #yourTable.Address syntax.

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.

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