Passing HTML string to my controller action method

I am using a rich text editor to type formatted text, as shown below:

I can get the HTML formatted text, which would look like this:

<p>This is my rich HTML Text</p>

Now I want to pass this HTML formatted text to my controller and my controller would put the text in an email and send it to the receiver.

The problem is HTML string is considered unsafe, so in order to pass it to my controller, I need to add [ValidateInput(false)] attribute to my Action method, like below:

    [ValidateInput(false)] // <-- not able to hit the action method without this
    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<JsonResult> Contact(string message)
    {
        if (!HttpContext.User.Identity.IsAuthenticated)
        {
            return Json(new { Authorize = "false" });
        }
    // email message to receiver
}

And this is the Ajax method which contacts the controller:

$(‘#contactBtn’).click(function () {
var form = $(‘#__AjaxAntiForgeryForm’);
var token = $(‘input[name=“__RequestVerificationToken”]’, form).val();
var message = quill.root.innerHTML; // <-- HTML formatted message

$.ajax({
    url: "/Communication/Contact",
    data: { __RequestVerificationToken: token, message: message },
    dataType: 'json',
    type: "POST"
});

});

So the above code works, but I am not sure if this is the right thing to do? Is there any security issue with the above code? Is there any encoding that I need to do on the HTML?

#ajax #asp.net #html

3 Likes48.80 GEEK