MVC Ajax.BeginForm和内容安全策略
本文关键字:安全策略 Ajax BeginForm MVC | 更新日期: 2023-09-27 18:29:15
为了防止跨端脚本,我在一个应用程序中实现了CSP。现在我正在重新配置所有的html类,以便javascript总是来自我的服务器。
现在,我找到了一个带有Ajax.BeginForm
的页面,如果我想提交表单并更新视图,总是会得到错误"Refused to evaluate a string as JavaScript because 'unsafe-eval' is not an allowed source of script in the following Content Security Policy directive: "script-src 'self'".
"。
有人能帮我吗,问题出在哪里?
这是我的html类(简称):
用户信息.cshtml:
<div id="OpenAccountInformation">@Html.Action("OpenAccountInformation")</div>
</div>
AccountInformation.chtml:
@Scripts.Render("~/Scripts/bundles/ManageUsers/AccountInformation")
@model Tumormodelle.Models.ViewModels.AzaraUserModel
<input type="hidden" value="@ViewBag.Editable" id="EditableUserInformation">
<div id="Editable">
@using (Ajax.BeginForm("EditUser", "ManageUsers", new AjaxOptions { InsertionMode = InsertionMode.Replace, UpdateTargetId = "OpenAccountInformation", HttpMethod = "post", }))
{
@Html.AntiForgeryToken()
@Html.HiddenFor(m => m.UserID)
<div>
<div>
@Html.LabelFor(m => m.Username, new { @class = "entryFieldLabel" })
</div>
</div>
<div>
<div>
<button name="button" value="save" class="formbutton" id="saveButton">save</button>
<button name="button" value="cancel" class="formbutton" id="cancelButton">cancel</button>
</div>
}
</div>
<div id="NonEditable">
<div>
<div>
@Html.LabelFor(m => m.Username, new { @class = "entryFieldLabel" })
</div>
</div>
<div>
<div>
<button name="button" value="edit" class="formbutton" id="editButton" type="button">edit</button>
</div>
</div>
</div>
和c方法:
public ActionResult EditUser(AzaraUserModel AzaraUserModel, string button)
{
if (button == Tumormodelle.Properties.Resources.Save)
{
if (ModelState.IsValid)
{
azaraUserManagement.Update(AzaraUserModel.Username, AzaraUserModel.Title, AzaraUserModel.FirstName, AzaraUserModel.LastName, AzaraUserModel.EMailAddress, null, AzaraUserModel.Phone, AzaraUserModel.UserID, (byte)AzaraUserModel.ShowMail.ID);
ViewBag.Message = Tumormodelle.Properties.Resources.Personal_Data_Changed;
ViewBag.Editable = true;
}
else ViewBag.Editable = false;
BindShowMailList();
return PartialView("AccountInformation", AzaraUserModel);
}
else
{
return RedirectToAction("OpenAccountInformation", "ManageUsers");
}
}
public ActionResult UserInformation()
{
return View("UserInformation");
}
public PartialViewResult OpenAccountInformation()
{
AzaraUserModel AzaraUserModel = new AzaraUserModel(azaraUserManagement.GetSingle(AzaraSession.Current.UserComparison.GetUser().Id));
BindShowMailList();
ViewBag.Editable = true;
return PartialView("AccountInformation", AzaraUserModel);
}
编辑:在Chrome调试器的帮助下,我发现错误是在表单被提交的那一刻抛出的。
Ajax.BeginForm
将在您的页面的生成HTML中生成内联脚本,而您在内容安全策略中使用script-src 'self'
禁止了该脚本。
如果您想使用CSP来阻止任何内联注入的脚本,则必须使用Html.BeginForm
,并在外部.js
文件中添加JavaScript以通过Ajax提交。
尝试将此属性添加到控制器的动作后
[ValidateInput(false)]