Special character encoding before going to the SQL database

Asked

Viewed 278 times

2

I am working with SQL Server 2008 and IIS7 to host my MVC website.

For security reasons, the website on which I work at the moment does not allow strings with special characters like '<' or '>' coming from a <textarea> are sent to the database.

How can I encode these characters and then decode them after fetching the string from the database? I want to be able to do something like:

  1. Encode special characters in Razorview in a string using Javascript
  2. Send the encoded string (which does not have the special characters) using a POST to the Controller of MVC
  3. Fetch the string from the database and decode, too, in the view

2 answers

3


You don’t need any of this. Just mark the Model or Viewmodel with [AllowHtml]:

[AllowHtml]
[DataType(DataType.MultilineText)]
public String MeuTextoHtml { get; set; }
  • The Data Anotattion AllowHtml prevent XSS attacks?

  • Got it +1. Here’s a reply interesting on the subject.

  • and this prevents code execution entered by input? (e.g. SQL Injection)

  • @ihavenokia If you use Entity Framework, yes.

  • yes use, thank you ;)

  • once I test your solution and make sure it works as expected, I will accept your answer as the most correct

  • If there are more questions about how to use it, just ask ;)

Show 3 more comments

0

HTML

First implements the function below, to create an element and take your html

function HtmlEncode(s)
{
    var el = document.createElement("div");
    el.innerText = el.textContent = s;
    s = el.innerHTML;
    el.remove();
    return s;
}

Then in your POST you encode the string and send

var conteudo=HtmlEncode($("#MinhaTextArea").val())
$.ajax({
    url: '/Meucontrole/MinhaAction',
    method:"Post",
    data:{parametro:conteudo},
    success: function (d) {
        //TODO:;
    }

})

Controller

In your controller you will receive the encoded string in the parameter parametro , to decode use System.Web.HttpUtility.HtmlDecode() and to code again System.Web.HttpUtility.HtmlEncode(t).

[HttpPost]
public ActionResult MinhaAction(string parametro)
{
    var decodificado = System.Web.HttpUtility.HtmlDecode(parametro);

    //TODO:;

    var codificado = System.Web.HttpUtility.HtmlEncode(decodificado);
    return View();
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.