【问题标题】:How to remove HTML tags from JSON response如何从 JSON 响应中删除 HTML 标签
【发布时间】:2018-03-06 17:54:18
【问题描述】:

对于管理员:我在这里检查了类似的主题,但很遗憾我没有找到答案。

我正在尝试从 http GET 响应中删除所有 html 标记。 我有一个用 ASP.NET MVC 编写的控制器,它调用一个数据库过程。这些过程返回存在 html 标记的 json。 应用程序是用 Angular4 框架编写的。 我认为剥离所有 html 标签并用这个标签替换它们的最佳位置是什么:

& --> &
 < --> &lt;
 > --> &gt;
 " --> &quot;
 ' --> &#x27;     &apos; not recommended because its not in the HTML spec (See: section 24.4.1) &apos; is in the XML and XHTML specs.
 / --> &#x2F;     forward slash is included as it helps end an HTML entity

MS SQL 数据库中的过程以这种方式返回 JSON 数据:

SELECT * FROM USERS FOR JSON AUTO

MVC 控制器接收到这个字符串并返回给应用程序:

object response= ExecuteProcedure("GetAllUsers");
return response;

在应用程序中我这样调用 API:

getJson(url: string): Observable<any> {
           return this.http.get(url).map(res => res.json()).catch(this.handleError);
}

让我感到困惑的是,为什么 XSS 在应用程序中不起作用,但在我直接从浏览器调用 API 时起作用。 我将不胜感激所有提示。

【问题讨论】:

  • 你的 MSSQL 版本是多少?
  • 我用的是 2017 版

标签: asp.net sql-server angular


【解决方案1】:

使用此功能删除 HTML 标签

说明。

1)RemoveHTMLTags(string str) 获取json字符串。

  1. 将 json 字符串与正则表达式“]*>”进行比较。

  2. 如果发现任何 HTMl 标记,请从 json 字符串中删除该标记。

  3. 返回没有 html 标签的 Json 字符串。

    public  string RemoveHTMLTags(string str)
     { 
         System.Text.RegularExpressions.Regex rx =
         new System.Text.RegularExpressions.Regex("<[^>]*>");
         str = rx.Replace(str, "");            
         return str;
     }
    

【讨论】:

  • 请对您的回答进行详细解释,以便下一位用户更好地理解您的回答。
  • 感谢您的宝贵时间。我希望现在很容易理解。
【解决方案2】:

这个怎么样

return this.http.get(url).map(res => {
   let theJson = res.json();
   let theString = theJson.stringify();
   return theString.replace(/<[^>]*>/g, '');
}).catch(this.handleError);

这假设您在标签之外的 html 中没有任何“”字符

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-14
    • 2021-02-22
    • 2021-12-16
    • 2021-11-16
    • 1970-01-01
    • 2021-06-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多