简体   繁体   English

ASP .NET MVC3 ViewBag 消毒字符串

[英]ASP .NET MVC3 ViewBag sanitizing string

So I need to pass to a JavaScript function an array of strings in my view based on data from the database.因此,我需要根据数据库中的数据在我的视图中将字符串数组传递给 JavaScript function。 So I have this code in the controller:所以我在 controller 中有这个代码:

        string top_six_string = "[";
        foreach (ObjectModel om in collection)
        {
            myProject.Models.BlobFile file = null;
            if (om.BlobFile != null)
            {
                file = om.BlobFile;
            }
            else if (om.BlobFiles.Count != 0) 
            {
                file = om.BlobFiles.First();
            }
            if (file != null)
            {
                top_six_string += " \"" + file.BlobFileID + "\",";
            }
        }
        top_six_string = top_six_string.TrimEnd(',');
        top_six_string += "]";
        ViewBag.TopSixList = top_six_string;

Now, I don't particularly understand why we have both a BlobFile field and a BlobFiles collection, but that's not that point.现在,我不太明白为什么我们同时拥有 BlobFile 字段和 BlobFiles 集合,但这不是重点。 The point is, debugging shows that I accurately the get the string I want (of the form ["25", "21", "61", "59"]).关键是,调试表明我准确地得到了我想要的字符串(形式为[“25”、“21”、“61”、“59”])。

But when running the JavaScript, I got the confusing error "Unexpected character &", and a little source-viewing in Chrome led me to learn that the string came out looking like this:但是在运行 JavaScript 时,我收到了令人困惑的错误“意外字符 &”,并且在 Chrome 中查看了一些源代码后,我了解到字符串看起来像这样:

[ "25", "21", "61", "59"]

So my assumption is that the ViewBag is sanitizing string that it is passed for display in HTML, but obviously that isn't my concern right now.所以我的假设是 ViewBag 正在清理字符串,它被传递以在 HTML 中显示,但显然这不是我现在关心的问题。 Am I correct in my assumption?我的假设是否正确? Is there another way to pass the view this information?是否有另一种方式来传递视图这些信息? Is there a way I can coerce the string back to quotes afterwards?有没有办法可以在之后将字符串强制转换回引号?

The problem is most likely when you output the contents of the ViewBag in your View.当您 output 在您的 View 中查看 ViewBag 的内容时,最有可能出现问题。 By default the Html helpers sanitize output to help protect against injection attacks.默认情况下,Html 助手清理 output 以帮助防止注入攻击。

What you want is this when outputting the value in your View: @Html.Raw(ViewBag.TopSixList)在视图中输出值时,您想要的是:@Html.Raw(ViewBag.TopSixList)

Since programmers barely use MVC3 and google shows this page also for Asp core由于程序员几乎不使用 MVC3,谷歌也为 Asp 核心显示了这个页面

In ASP.Net Core change this line:在 ASP.Net Core 中更改此行:

ViewBag.TopSixList = top_six_string;

To

ViewBag.TopSixList = new HtmlString(top_six_string);

And add using Microsoft.AspNetCore.Html;使用 Microsoft.AspNetCore.Html 添加; if HtmlString is not accessible.如果HtmlString不可访问。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM