Ajax Post提交参数的值中带有html标签不能提交到后端的解决办法(ASP.NET)

我们在做Web开发的时候,在MVC中当前端通过Ajax提交数据到后端时,当数据的值中带有HTML标签时,可以是出于安全性方面,在后端的Controller的Action方法中是不会接收到这个Ajax请求的 (路由到相应Action方法之前已出错,通过error属性回调中的xhr.responseText可以得到如下的错误信息 )。

Ajax Post提交参数的值中带有html标签不能提交到后端的解决办法(ASP.NET)_第1张图片

解决方法:可以在前端提交数据时先将带有HTML标签的数据用encodeURIComponent或escape(用encodeURI某些情况还是不能解决此问题)或Base64,比如btoa函数(需要注意:btoa不支持中文,需要先进行转换字节编码处理)编码,提交后在后端进行HttpUtility.UrlDecodeBase64(比如Convert.FromBase64String函数)解码再处理。Load数据到页面的时候无需处理。

 

一. 用encodeURI编码不一定可行(测试案例)

 用encodeURI编码,在测试的时候在遇到Workaround值为以下数据时,依然出现潜在安全错误无法提交,改用escape或encodeURIComponent()编码时则可以解决通过,(但需注意,escape已从W3C标准中废弃)






?Actual Issue: replication issue in the SLT system ?








Actual Action Taken:?ZMRFTRANS table in HANA database was dropped and reloaded from ECC, the reload job was load balanced and it's priority set to 1

Ajax Post提交参数的值中带有html标签不能提交到后端的解决办法(ASP.NET)_第2张图片

 Ajax Post提交参数的值中带有html标签不能提交到后端的解决办法(ASP.NET)_第3张图片

 

 二. 可行方法:

1. 用encodeURIComponent或escape方法对提交的值进行URI编码

前端提交数据:

Ajax Post提交参数的值中带有html标签不能提交到后端的解决办法(ASP.NET)_第4张图片

后端Action方法:

Ajax Post提交参数的值中带有html标签不能提交到后端的解决办法(ASP.NET)_第5张图片

 

2. 可行方法:用btoa方法对提交的值进行Base64编码:

由于btoa不支持“非单字节”字符,直接用btoa编码中文会出错,需先对中英文字符都统一转换为“单字节”字符处理(以下提供MND官方文档的转换方法):

Ajax Post提交参数的值中带有html标签不能提交到后端的解决办法(ASP.NET)_第6张图片

If you need to encode Unicode text as ASCII using btoa(), one option is to convert the string such that each 16-bit unit occupies only one byte. For example:

//Base64编码中文时的转换处理方法:
// convert a Unicode string to a string in which each 16-bit unit occupies only one byte
function toBinary(string) {
  const codeUnits = new Uint16Array(string.length);
  for (let i = 0; i < codeUnits.length; i++) {
    codeUnits[i] = string.charCodeAt(i);
  }
  return String.fromCharCode(...new Uint8Array(codeUnits.buffer));
}

// a string that contains characters occupying > 1 byte
const myString = "☸☹☺☻☼☾☿";

const converted = toBinary(myString);
const encoded = btoa(converted);
console.log(encoded);                 // OCY5JjomOyY8Jj4mPyY=

If you do this, of course you'll have to reverse the conversion on the decoded string:

//Base64解码中文时的转换处理方法:
function fromBinary(binary) {
  const bytes = new Uint8Array(binary.length);
  for (let i = 0; i < bytes.length; i++) {
    bytes[i] = binary.charCodeAt(i);
  }
  return String.fromCharCode(...new Uint16Array(bytes.buffer));
}

const decoded = atob(encoded);
const original = fromBinary(decoded);
console.log(original);   

前端提交数据: 

Ajax Post提交参数的值中带有html标签不能提交到后端的解决办法(ASP.NET)_第7张图片

后端Action方法: 

Ajax Post提交参数的值中带有html标签不能提交到后端的解决办法(ASP.NET)_第8张图片

 

 题外篇:

以下是网上结合“URI编码”来解决“Base64不能直接将中文编码”的问题:

https://www.jianshu.com/p/04ab0f0e86de

function utf8_to_b64(str) {
    return window.btoa(unescape(encodeURIComponent(str)));
}
function b64_to_utf8(str) {
    return decodeURIComponent(escape(window.atob(str)));
}

Ajax Post提交参数的值中带有html标签不能提交到后端的解决办法(ASP.NET)_第9张图片

你可能感兴趣的:(.Net,Javascript,HTML)