Encoding and decoding data the way MVC likes it

2019-08-11 11:46发布

问题:

I get data from MVC and encode it using HttpUtility.HtmlEncode. The problem is that MVC is not fond of form values containing the ampersand (&) symbol. For example, this...

HttpUtility.HtmlEncode("'");

...results in '. I fetch it on a GET, but if I submit this on a POST, I see the following action error:

Exception = {"A potentially dangerous Request.Form value was detected from the client (selection=\"'...\")."}

How can I encode my data on a GET in a way that makes MVC happy on a POST? I cannot set the property to [AllowHtml] because the model is within a separate class in a 3rd party DLL that I do not have control over, nor can I re-implement it, it seems.

回答1:

Instead of dealing with Encoding and Decoding Urls just post the Base64String



回答2:

I found a better way of serializing/deserializing and I wanted to share it with everyone. Since I am using JavaScript and DataTables.NET to do AJAX POST requests, I was able to use the System.Web.Helpers methods called Json.Encode and Json.Decode, since they convert directly to JSON (JavaScript Object Notation) and back, it seems to work perfectly from JavaScript and up to MVC for my needs, and I should have used it all along.



回答3:

How about using UrlEncode instead? https://msdn.microsoft.com/en-us/library/system.web.httputility.urlencode(v=vs.110).aspx