将HTML通过AJAX调用传递给C#MVC控制器。 500错误

时间:2015-10-02 15:44:04

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

所以我对这个感到有点难过。我有多个页面通过各种数据为后端的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.');
            }
        });

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

[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请求中的newContent参数中data设置为<p>hello</p>之类的任何内容时,这些写法不会被调用,而且整个ajax调用失败。然而,当我只使用普通的字符串,例如hello它运作正常。我进一步将其缩小到只是打开html括号,所以即使<p也会失败。

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

1 个答案:

答案 0 :(得分:7)

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; }
}