【问题标题】:Passing HTML over AJAX call to C# MVC Controller. 500 Error通过 AJAX 调用将 HTML 传递给 C# MVC 控制器。 500 错误
【发布时间】:2015-12-30 21:16:42
【问题描述】:

所以我有点被这个难住了。我有多个页面在后端使用各种数据对我的 C# 控制器进行了很多成功的 Ajax 调用,但现在我正在尝试构建一个简单的小内容管理功能,因此更新数据库中的 HTML来自 JS 编辑器的新 HTML。

长话短说,我已经删除了所有繁重的数据库代码并将其缩小到我的控制器不接受任何带有 html 标记的内容,或者我的 ajax 代码无法发送它。

Ajax函数是:

$.ajax({
            type: "POST",
            url: '@Url.Action("UpdateContent", "Admin")',
            data: {
                elementId: elementId,
                newContent: newContent
            },
            dataType: "json",
            success: function (data) {
                if (data.result == 'true') {
                    infoMessage('Content Updated!', 'success');
                } else {
                    infoMessage('Error: ' + data.result + '. Nothing has been updated!', 'error');
                }
            },
            error: function () {
                alert('There was a problem contacting the server.');
            }
        });

在我的 Controller 方面,我已经删除了所有代码,只留下了一些调试写入行。

[HttpPost]
    public ActionResult UpdateContent(string elementId, string newContent)
    {
        System.Diagnostics.Debug.WriteLine("!" + elementId);
        System.Diagnostics.Debug.WriteLine("!" + newContent);
        string _result = "true";
        return Json(new { result = _result });
    }

现在有趣的是,当我将 Ajax 请求中的 data 参数中的 newContent 设置为 <p>hello</p> 之类的任何内容时,这些 writelines 甚至都不会被调用,并且整个 ajax 调用都会失败。然而,当我只使用普通字符串时,例如hello 它工作正常。我已将其进一步缩小到仅打开 html 括号,因此即使 <p 也会失败。

考虑到这一点,这里发生了什么?其次,通过 Ajax 将 html 发送回控制器的正确方法是什么,这样就不会发生这种情况?

【问题讨论】:

  • 500 是内部服务器错误。调试没有显示任何异常?

标签: javascript c# jquery ajax asp.net-mvc


【解决方案1】:

ASP.NET 默认启用request validation 以帮助防止 XSS。您可以通过将ValidateInput 属性添加到您的操作来禁用此功能:

[HttpPost]
[ValidateInput(false)]
public ActionResult UpdateContent(string elementId, string newContent)
{
    System.Diagnostics.Debug.WriteLine("!" + elementId);
    System.Diagnostics.Debug.WriteLine("!" + newContent);
    string _result = "true";
    return Json(new { result = _result });
}

您还需要将以下内容添加到您的web.config:

<httpRuntime requestValidationMode="2.0" />

一种更新(更好)的替代方法是使用AllowHtml 属性,您可以将其应用于模型上的属性。这是首选,因为您只允许此道具绕过验证,而不是整个请求。

class MyModel
{
    [AllowHtml]
    public string MyHtml { get; set; }
}

【讨论】:

    猜你喜欢
    • 2018-09-30
    • 1970-01-01
    • 2016-11-08
    • 1970-01-01
    • 2020-02-26
    • 2017-09-30
    • 2011-12-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多