I am using MVC with model first. I used [ValidateInput(false)]
on my controller which accepts a rich text input. This worked fine. Now I found the following post which allows me to use [AllowHtml]
which I would prefer (post).
[MetadataType(typeof(YourEntityMetadata))]
public partial class YourEntityClass
{
}
public class YourEntityMetadata
{
[AllowHtml]
public string YourPropertyWithHtml { get; set; }
}
I tried this but it did not work. For test reasons, I added AllowHtml
directly onto the property in the auto-generated model, which also did not work. In both cases I got the same error "Potentially dangerous request..."
The input in question is a simple rich text <p> lorem <\p>
from CKEditor.
The controller calls a separate function which does the actual writing to access to the database, and the access to the model first ModelContainer.
Is there something in the auto-generation which might prevent the [AllowHtml]
to work. Is it a problem that the controller does not directly access or create the entity but passes the string to another function which creates the entity and saves it to the database?
EDIT
I disabled the filters which check for the XSRF token. I have the request validation mode set:
<httpRuntime targetFramework="4.6.1" requestValidationMode="2.0" />
I stripped down the controller method to:
public int SaveBlock(string blockCont)
{
var testt = new ViewTest() { BlockContent = blockCont };
return 0;
}
with a simple view model:
public class ViewTest
{
[AllowHtml]
public string BlockContent { get; set; }
}
and still the request is marked with a "potentially dangerous" error.
I read a bit more into the issue with the useful comments in mind. My confusion was that I thought the data annotations are applied when data is written into the model not when it is accepted in the controller method.
So of course my approach to send a string to the controller and to hope that it is validated when I actually write it into the model was wrong. Perhaps I wanted a bit too much.
For my approach, in which I want to separate out my data models from the controller as much as possible (using a repository), I guess the only way forward would be a view model of the input sent to the controller. However, in my case I suppose I will stick to encoding the few non-html string inputs, to let only the one html input through to the database.