Receiving "potentially dangerous Request.Form" with requestValidationMode = 2.0 - c#

I'm trying to pass raw HTML using ViewBag and Html.Raw, I have another instance of logic identical to this that works in my app but when I duplicated it on another page I'm getting this error again.
I have already enabled <httpRuntime requestValidationMode="2.0" /> in my config file. Why am I still getting this message? Shouldn't this allow it across the entire application?

Give [ValidateInput(false)] in your method.

Related

Random Invalid Viewstate Error

I know there are a lot of questions on this topic and I have read them all.
I'm using IIS8, .Net 4.5.
Users randomly get an invalid viewstate error, I can't figure it out. Once this happens the only way they can get back into the site is to clear browser cache.
In my web.config I have:
<system.web>
<machineKey validationKey='....key here' decryptionKey='....decrypt key is valid here' validation='SHA1'/>
<!--<hostingEnvironment shadowCopyBinAssemblies="false" />-->
<authentication mode="None" />
<compilation targetFramework="4.5.1" />
<httpRuntime targetFramework="4.5.1" />
...
</system.web>
I'm running on a virtual private server, and I've yet to find a viewstate larger than 9kb.
My application pool is set to restart at 3:00am, once per day.
My page uses update panels, maybe the user is clicking 'back'? But I've seen it happen just visiting the page with no clicking back.
One thing I noticed is I have 3 different sites using the same application pool identity, but the application pools are seperate. There is no machine keys in machine.xml, but only in my web.config.
A couple of possibilities to investigate:
Update panels are changing form field values (which are what is used to compute ViewState), then the page gets POSTed back to the server, where the new values make validation fail. See this post
You have caching enabled (perform a trace of HTTP headers - make sure you don't have dev tools open) which is causing invalid ViewState to be generated w/ UpdatePanel gumming things up.
Are you using Server.Execute anywhere? (see above link for same)
(less likely) Does your "Virtual Private Server" get migrated to different hardware (perhaps without you knowing it)?

asp.net Unable to validate data

I am getting this error, and I know what causes it. There are many causes, but in my case, the issue is that the machinekey differs from server to server (in the web farm) and therefore when it jumpes from machine to machine, it can't decrypt viewstate and/or cookies . I've since fixed this issue, however, there are some users still left with a cookie on their machine, written with the old machinekey, and they are getting this error. I need a good way to handle this error, log them out and then redirect back to the login page. I've tried putting an exception handler in global.asax in Application_error, but this doesn't seem to fire for this error. There are other errors that happen, and I've filtered to catch only this error (by looking at the exception). I have customErrors 'on' in the web.config. How do I do this?
There are a few ways to resolve this issue. The best overall solution is to set the encryption and decryption keys explicitly in the machine.config of each server:
<machineKey validationKey="JFDSGOIEURTJKTREKOIRUWTKLRJTKUROIUFLKSIOSUGOIFDS..." decriptionKey="KAJDFOIAUOILKER534095U43098435H43OI5098479854" validation="SHA1" />
Another option is to disable encryption of the ViewState altogether, but you will lose some security benefits by doing this:
<pages viewStateEncryptionMode="Never" />
Lastly, you can disable the validation:
<pages enableViewStateMac="false" ... />

Invalid Webmethod name

I created a web method but when i go to the site and type for example http://mysite.com/services/Amounts/GetAmount it returns an error Internal Server Error 500. After investigating the issue in event logs etc,, it says GetAmount invalid method name. but i know the mame is fine
[WebMethod(EnableSession=true)]
public string GetAmount(Amounts amts)
{
//some logic here to add to the database.
}
What are the possible issues that I have to look into when this type of error shows?, I checked all the references and everything is named properly "GetAmount".
What are you trying to do here? You need to post more code and web.config. Which version of .NET you are using here? All this information may get you the better answer.
Firstly, your URL http://example.org/services/Amounts/GetAmount does not seems to be correct - there has to be .asmx somewhere unless you are using ASP.NET routing or some url rewriting.
Assuming that your routing/re-writing is indeed working correctly:
in general, if its a normal SOAP Web Service then enable HTTP get -
<webServices>
<protocols>
<add name="HttpGet" />
<add name="HttpPost" />
</protocols>
</webServices>
If you are trying create a service callable from script (ScriptService) then for asmx service, you need to mark the method as ScriptService and you may need to adjust web.config based on your .NET version. Also you need to enable HTTP GET - for example,
[ScriptMethod(UseHttpGet = true)]
public string GetAmount(Amounts amts)
You may also need to adjust Response Format whether you want JSON or XML.

ASP.net dangerous submission error

When I try and run a forum page:
System.Web.HttpRequestValidationException: A potentially dangerous Request.Form value was detected from the client
In my web.config I have:
<pages validateRequest="false" smartNavigation="false">
And on the actual page I also have:
<%# Page Language="C#" AutoEventWireup="true" ValidateRequest="false" MasterPageFile="~/MasterPages/Main.master" %>
But it keeps throwing this error!
Edit
I fixed it with:
<httpRuntime requestValidationMode="2.0" />
But what's that do and why does it work?
This error occurs because something in the submitted form, or in the querystring, looked dangerous to the validation in ASP.NET.
By adding
<httpRuntime requestValidationMode="2.0" />
you are relaxing the validation that is applied back to the standards of ASP.NET 2.
I would say you are far better off trying to work out exactly what it objects to in your form/querystring than just relaxing the validation. This tightened validation is there to protect you and your users, and shouldn't be relaxed lightly.
I have recently hit this on a project I am working on when we upgraded to ASP.NET MVC3 (from version 2). In our case it actually highlighted an issue whereby we were urlencoding our querystring when we didn't mean to (i.e. the entire quertstring including the question mark and the ampersands was all getting url encoded when it shouldn't be).
Whatever your reason, look for the root cause rather than relax the validation if it is at all possible.
There was probably markup in the submitted text. http://www.asp.net/learn/whitepapers/aspnet4/breaking-changes
The request validation feature in
ASP.NET provides a certain level of
default protection against cross-site
scripting (XSS) attacks. In previous
versions of ASP.NET, request
validation was enabled by default.
However, it applied only to ASP.NET
pages (.aspx files and their class
files) and only when those pages were
executing.
In ASP.NET 4, by default, request
validation is enabled for all
requests, because it is enabled before
the BeginRequest phase of an HTTP
request. As a result, request
validation applies to requests for all
ASP.NET resources, not just .aspx page
requests. This includes requests such
as Web service calls and custom HTTP
handlers. Request validation is also
active when custom HTTP modules are
reading the contents of an HTTP
request.
As a result, request validation errors
might now occur for requests that
previously did not trigger errors. To
revert to the behavior of the ASP.NET
2.0 request validation feature, add the following setting in the
Web.config file:
<httpRuntime requestValidationMode="2.0" />

How to increase the POST size for an ASMX web service?

Background
I am developing an ASP.Net server side control that needs to talk to an ASMX web service. The server side control uses a WebClient object to talk to the web service, since it needs to be reused often in various application, and to make it easier on the developers, they are not required to create a service reference to the web service.
Implementation
During the use of the control, it is requires the sending of a serialised object to the web service. The object is serialised using the XmlSerializer and the resulting XML string is then compressed using the chilkat compression library. The web service call for the control looks as follows:
webClient.UploadStringAsync(new Uri(serviceHost + serviceMethod), "POST", sendData)
The content of sendData (string) is compressedResponse={CompressedData}.
The web service has a method defined as follows to receive the data and then decompress the string value using the chilkat library before de-serialising the object using the XmlSerializer.
public void SaveResponse(string compressedResponse)
The communication between the control and the service is working. Initially there were no settings or binding defined in the web.config for any of the above. After initial searching I did add
<httpRuntime maxRequestLength="20480"/>
to both the client and server web.config files. This has made no difference.
Problem
Compressed or uncompressed the data being posted to the web service in the sendData variable is to big for a normal POST request, and is corrupted. This is confirmed when checking the last few characters of the string before and after it being posted to the server in compressed format, and uncompressed, the Xml document is missing the last root tag when checking in the debugger. The string can't be decompressed and therefore the service call fails every time.
How do I increase the POST size for the WebClient request to ensure that the full string is received by the server?
I have looked at the various option on Google, but none are giving me a good enough sample of where to make the changes, or samples of what the changes need to look like. I am completely lost as to whether the change needs to be made on the server or the consuming website, and since there are no binding defined for this, how to create a binding in the web.config for an ASMX HTTP service call.
I believe you must be hitting ASP.NET max request length limit. That you can modify via config file such as:
<system.web>
<httpRuntime executionTimeout="240" maxRequestLength="20480" />
</system.web>
maxRequestLength value is in KB, so above setting would allow 20 MB. You can also apply the setting only to selected URLs using location tag e.g.
<location path="yourservice.asmx">
<system.web>
<httpRuntime executionTimeout="240" maxRequestLength="20480" />
</system.web>
</location>
There seems to be no way to change the POST size for a ASMX Web Service when only HttpPost is enabled.
The solution in the end was to switch the service to running HttpSoap and create a service reference to the assembly containing the control. Once done the binding is created using code in the control once the endpoint is set via a property.

Categories

Resources