简体   繁体   中英

Razor, asp.net, C#: how to validate a form field that is required and allows HTML snippets?

I am using Razor do a single proof-of-concept cshtml page, no controller. I use ASP.NET 4.5.

This page has a form. Its action points to this page too. So when the form is submitted, it goes to the same page.

The form has a field called "description". It is a required field, but allow users to enter html snippets.

I have the following to check user input:

Validation.RequireField("description", "Description is required.");

However, when a user enters html snippets in the "description" field and submits the form, the website shows the following error message:

    A potentially dangerous Request.Form value was detected from the client (Description="<p>This bilingual.....
....
Line 43:             description = Request.Form["description"];
.....

This page is in a VERY safe environment and so html snippets are allowed.

Let's put best practices aside. How can I make the description field required and allow html snippets at the same time? I have more than one field in the form that allow html snippets.

I hope to find a solution that does not touch web.config.

Regards and thanks.

I tried the solution suggested by mxmissle, it did not work for me. I have just a single cshtml page which has a form as well as the post processing code.

I read many online posts, but unable to find one that works for me. Eventually, I tried something so simple that works. Instead of using

description = Request.Form["description"];

use

description = Request.Unvalidated["description"];

The later get the user input with html tags without any runtime complaint. Also

Validation.RequireField("description", "Description is required.");

still works.

Interestingly enough, I found so many online posts about this error message and none of them talks about Request.Unvalidated. I am not sure what I did is the right way, but it works for me. If anybody knows a better way, please let me know.

Hope this helps someone else.

I suggest you simply add following attribute to your model property.

[AllowHtml]
MyHtml

Add the following to your controller class:

[HttpPost]
[ValidateInput(false)]

or

[HttpGet]
[ValidateInput(false)]

Just remember that by doing this, you are opening yourself up to attacks. So be sure you have taken the appropriate steps to make your site secure.

Not recommended but adding this to your web.config should do the trick.

<system.web>
  <httpRuntime requestValidationMode="2.0" />
</system.web>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM