IE中的JSON安全警告,尝试在MVC3应用程序中下载

时间:2012-05-03 21:32:22

标签: json asp.net-mvc-3 c#-4.0 jquery

在我研究过同样的问题时,我在这里看到了很多关于SO的问题,但是没有任何答案对我有帮助。

我已经尝试了每个答案解决方案,但没有一个有效。

所以我会逐一列出代码以及我尝试过的代码和位置。

首先,我的观点包括2个表格和部分视图,主要观点如下:

@using MyApplication.Select.Web.Helpers; 
@model SearchUsersViewModel

@*Scripts*@
<script src="@Url.Content("~/Scripts/SearchEntity.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/ManageUsers.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/FormValidation.js")" type="text/javascript"></script>

<script type="text/javascript">

    var theme = "admin"; //(lender, school, admin, or public)
    var cssArray = ["ManageUsers.css", "ActionIcons.css"];

    //Invoke loadCSS Method from CSSLoader.js
    loadCSS(theme, cssArray);

    //Set active tab from NavigationAdmin.js
    setActiveNavTab("tab01"); //(tab01, tab02, tab03, tab04, tab05, tab06)

    document.getElementById("AdminPageHeaderIMG").className = "HeaderImageManageUsers";

</script>

<div>
    <table id="" cellpadding="0" cellspacing="0" border="0">
        <tr style="height: 60px;">
            <td>
                <div class="PageHeaderDescriptionDiv">
                    Welcome to My Application
                </div>
            </td>
        </tr>
        <tr style="height: 1px;">
            <td class="ContentDividerHoriz"></td>
        </tr>
    </table>
    <table class="SearchUsersMainTable" cellpadding="0" cellspacing="0" border="0">
        <tr>
            <td>
                <table cellpadding="0" cellspacing="0" border="0">
                    <tbody>
                        <tr>
                            <td>
                                <div class="SearchByUserDataTable">
                                    @using (Html.BeginForm()) {
                                        @Html.HiddenFor(model => model.SearchFilterType)
                                        <table cellpadding="0" cellspacing="0" border="0">
                                            <tr style="height: 30px;">
                                                <td class="Header01">
                                                    User Search
                                                </td>
                                            </tr>
                                        </table>
                                        <table cellpadding="0" cellspacing="0" border="0">
                                            <tr style="height: 20px;">
                                                <td class="Header02">
                                                    Search By User Information
                                                </td>
                                            </tr>
                                        </table>
                                        <table cellpadding="0" cellspacing="0" border="0">
                                            <tr style="height: 1px;">
                                                <td class="ContentDividerHoriz_425"></td>
                                            </tr>
                                        </table>
                                        <table id="searchByUserDataTable" cellpadding="0" cellspacing="0" border="0">
                                            <tr style="height: 26px;">
                                                <td class="leftColumn">
                                                    @Html.LabelFor(model => model.LastName)
                                                </td>
                                                <td class="rightColumn">
                                                    @Html.TextBoxFor(model => model.LastName, new { @class = "TextField_220" })
                                                </td>
                                            </tr>
                                            <tr style="height: 26px;">
                                                <td class="leftColumn">
                                                    @Html.LabelFor(model => model.Username)
                                                </td>
                                                <td class="rightColumn">
                                                    @Html.TextBoxFor(model => model.Username, new { @class = "TextField_220" })
                                                </td>
                                            </tr>
                                            <tr style="height: 26px;">
                                                <td class="leftColumn">
                                                    @Html.LabelFor(model => model.EmailAddress)
                                                </td>
                                                <td class="rightColumn">
                                                    @Html.TextBoxFor(model => model.EmailAddress, new { @class = "TextField_220" })
                                                </td>
                                            </tr>
                                        </table>
                                        <table cellpadding="0" cellspacing="0" border="0">
                                            <tr>
                                                <td id="filterByUserError" style="width: 300px; color: #ff0000;"></td>
                                                <td align="right" style="width: 50px;">
                                                    <div>
                                                        <input id="filterByUserButton" type="submit" value="Search" />
                                                    </div>
                                                </td>
                                                <td style="width: 75px;"></td>
                                            </tr>
                                        </table>
                                    }
                                </div>
                            </td>
                            <td style="width: 20px;"></td>
                            <td>   
                                <div class="SearchByEntityDataTable">
                                    @using (Html.BeginForm()) { 
                                        <table cellpadding="0" cellspacing="0" border="0">
                                            <tr style="height: 28px;">
                                                <td style="width: 425px;"></td>
                                            </tr>
                                        </table>
                                        <table cellpadding="0" cellspacing="0" border="0">
                                            <tr style="height: 20px;">
                                                <td class="Header02">
                                                    Search By Entity Information
                                                </td>
                                            </tr>
                                        </table>
                                        <table cellpadding="0" cellspacing="0" border="0">
                                            <tr style="height: 1px;">
                                                <td class="ContentDividerHoriz_425"></td>
                                            </tr>
                                        </table>
                                        <table id="searchByEntityDataTable" cellpadding="0" cellspacing="0" border="0">
                                            <tr style="height: 26px;">
                                                <td class="leftColumn">
                                                    @Html.LabelFor(model => model.EntityTypeID)
                                                </td>
                                                <td class="rightColumn">
                                                    @Html.DropDownListFor(model => model.EntityTypeID, new SelectList(Model.EntityTypes, "ID", "Name"), new { id = "entityTypeDropDown", @class = "DropDown_220" })
                                                </td>
                                            </tr>
                                            <tr style="height: 26px;">
                                                <td class="leftColumn">
                                                    @Html.LabelFor(model => model.SearchField, new { id = "entityTypeSearchLabel"})
                                                </td>
                                                <td class="rightColumn">
                                                    @Html.TextBoxFor(model => model.SearchField, new { id = "entityTypeSearchField", @class = "ui-widget TextField_220" })
                                                </td>
                                            </tr>
                                            <tr style="height: 26px;">
                                                <td class="leftColumn"></td>
                                                <td class="rightColumn"></td>
                                            </tr>
                                        </table>
                                        <table cellpadding="0" cellspacing="0" border="0">
                                            <tr>
                                                <td id="filterByEntityError" style="width: 300px; color: #ff0000;"></td>
                                                <td align="right" style="width: 50px;">
                                                    <div>
                                                        <input id="filterByEntityButton" type="submit" value="Search" />
                                                    </div>
                                                </td>
                                                <td style="width: 75px;"></td>
                                            </tr>
                                        </table>
                                    }
                                </div>
                            </td>
                        </tr>
                    </tbody>
                </table>
                <table cellpadding="0" cellspacing="0" border="0">
                    <tr style="height: 1px;">
                        <td class="ContentDividerHoriz"></td>
                    </tr>
                </table>
                <table cellpadding="0" cellspacing="0" border="0">
                    <tr style="height: 33px;">
                        <td style="width: 870px;">
                            <div class="TelerikGridHeaderBkgd">
                                <table cellpadding="0" cellspacing="0" border="0">
                                    <tr>
                                        <td class="Header01" style="width: 150px; padding: 0px 0px 4px 5px;">
                                            User Search Results
                                        </td>
                                        <td style="width: 10px;"></td>
                                        <td style="width: 710px;">
                                            <table cellpadding="0" cellspacing="0" border="0">
                                                <tr style="height: 4px;">
                                                    <td style="width: 710px;"></td>
                                                </tr>
                                            </table>
                                            <table>
                                                <tr style="height: 20px;">
                                                    <td style="width: 188px;">
                                                        @*Resend Invitation*@
                                                        <table cellpadding="0" cellspacing="0" border="0">
                                                            <tr>
                                                                <td class="ActionIcon_ResendInvitationOn"></td>
                                                                <td style="padding-left: 5px; padding-right: 10px;">
                                                                    <span class="SearchUsersLegendText">= Resend Invitation</span> 
                                                                </td>
                                                            </tr>
                                                        </table>
                                                    </td>
                                                    <td style="width: 140px;">
                                                        @*Account Approved Status*@
                                                        <table width="140" cellpadding="0" cellspacing="0" border="0">
                                                            <tr>
                                                                <td class="ActionIcon_AccountStatusLegend"></td>
                                                                <td style="padding-left: 5px; padding-right: 10px;">
                                                                    <div class="SearchUsersLegendText">
                                                                        <span>= </span> 
                                                                        <span style="color: #839f1b;">Active</span>
                                                                        <span> / </span>
                                                                        <span style="color: #d6161f;">Inactive</span>
                                                                    </div>
                                                                </td>
                                                            </tr>
                                                        </table>
                                                    </td>
                                                    <td style="width: 162px;">
                                                        @*Account Lock Status*@
                                                        <table cellpadding="0" cellspacing="0" border="0">
                                                            <tr>
                                                                <td class="ActionIcon_UnlockAccountOn"></td>
                                                                <td style="padding-left: 5px; padding-right: 10px;">
                                                                    <span class="SearchUsersLegendText">= Unlock Account</span> 
                                                                </td>
                                                            </tr>
                                                        </table>
                                                    </td>
                                                    <td style="width: 170px;">
                                                        @*Reset Password*@
                                                        <table cellpadding="0" cellspacing="0" border="0">
                                                            <tr>
                                                                <td class="ActionIcon_ResetPasswordOn"></td>
                                                                <td style="padding-left: 5px; padding-right: 10px;">
                                                                    <span class="SearchUsersLegendText">= Reset Password</span> 
                                                                </td>
                                                            </tr>
                                                        </table>
                                                    </td>
                                                    <td style="width: 145px;">
                                                        @*Edit Account*@
                                                        <table cellpadding="0" cellspacing="0" border="0">
                                                            <tr>
                                                                <td class="ActionIcon_EditOn"></td>
                                                                <td style="padding-left: 5px; padding-right: 10px;">
                                                                    <span class="SearchUsersLegendText">= Edit Account</span> 
                                                                </td>
                                                            </tr>
                                                        </table>
                                                    </td>
                                                </tr>
                                            </table>
                                            <table>
                                                <tr style="height: 6px;">
                                                    <td style="width: 710px;"></td>
                                                </tr>
                                            </table>
                                        </td>
                                    </tr>
                                </table>
                            </div>
                        </td>
                    </tr>
                    <tr>
                        <td style="width: 870px;">
                            <div id="searchResults">
                                @Html.Partial("SearchResultsPartial", Model)
                            </div>
                        </td>
                    </tr>
                </table>
            </td>
        </tr>
    </table>
</div>

SearchResultsPartial在这里:

@model SearchUsersViewModel

@*Scripts*@
<link href="@Url.Content("~/Content/styles/TelerikCustom.css")" rel="stylesheet" type="text/css" />

@(Html.Telerik().Grid(Model.Users)
    .Name("Users").TableHtmlAttributes(new { style = "width: 870px;"})
    .Columns(columns => {
        columns.Bound(o => o.EntityTypeName).Title("Entity Type");
        columns.Bound(o => o.FirstName).Title("First Name");
        columns.Bound(o => o.LastName).Title("Last Name");
        columns.Bound(o => o.Username).Title("Username");
        columns.Template(
            @<text>
                <a href="mailto:@item.EmailAddress" target="blank">@item.EmailAddress</a>
            </text>).Title("Email").HtmlAttributes(new { style = "text-align: center" }).HeaderHtmlAttributes(new { style = "text-align: center" });
        columns.Template(
            @<text>
                 @{ if (@item.MembershipID == 0) {
                        <div class="ActionIcon_ResendInvitationOn" title="Resend Invitation" onclick="resendInvitation(@item.EntityID, @item.EntityTypeID, '@item.EmailAddress')"></div>
                    }
                    else {
                        if ((bool) item.IsApproved) {
                            <div class="ActionIcon_AccountStatusOn" title="Disable Account" onclick="setApprovalStatus('@item.Username', false)"></div>
                        }
                        else {
                            <div class="ActionIcon_AccountStatusOff" title="Enable Account" onclick="setApprovalStatus('@item.Username', true)"></div>
                        }
                        if ((bool) item.IsLockedOut) {
                            <div class="ActionIcon_UnlockAccountOn" title="Unlock Account" onclick="unlockAccount('@item.Username')"></div>
                        }
                        else {
                            <div class="ActionIcon_ResetPasswordOn" title="Reset Password" onclick="resetPassword('@item.Username')"></div>
                        }
                        <div class="ActionIcon_EditOn" title="Edit User" onclick="location.href='@Url.Action("Edit", "Admin", new { id = item.MembershipID, username = item.Username })'"></div>
                    }
                 }
            </text>).Title("Actions");
        columns.Bound(o => o.RowNumber).Hidden(true);
        columns.Bound(o => o.MembershipID).Hidden(true);
        columns.Bound(o => o.EntityID).Hidden(true);
        columns.Bound(o => o.EntityTypeID).Hidden(true);
    })
)

<div>
     Total Rows:
    @{
        if (!@Model.Users.Any()) {
            @Html.Label("0")
        }
        else {
            @Model.Users.First().TotalRows
        } 
    }
</div>

任何一种形式都可以进行搜索,这是一种互斥搜索。按用户数据搜索或按实体数据搜索,但不能同时搜索两者。每个表单上的提交按钮都会触发自己运行ajax调用的javascript:

function filterByUserSearch() {

    var lastName = document.getElementById("LastName");
    var username = document.getElementById("Username");
    var emailAddress = document.getElementById("EmailAddress");
    var entityTypeID = document.getElementById("entityTypeDropDown");
    var entityName = document.getElementById("entityTypeSearchField");
    var searchFilterType = document.getElementById("SearchFilterType");

    //alert("User Search");
    entityTypeID.value = 0;
    entityName.value = "";
    searchFilterType.value = 0;
    $.ajax({
        url: "/Admin/Search/",
        dataType: "json",
        cache: false,
        type: 'POST',
        contentType: 'application/json; charset=utf-8',
        data: { LastName: lastName.value, Username: username.value, EmailAddress: emailAddress.value, SearchFilterType: searchFilterType.value },
        success: function (result) {
            $('#resultSpan').html('');
            if(result.Success) {
                $('#searchResults').html(result.Data);
                if (result.ResultMessage != '<li></li>') {
                    $('#resultSpan').append($("<ul id='successMsg' style='list-style: none;' />").append(result.ResultMessage)).addClass("AjaxSuccessText");
                    $('#successMsg').css("padding-left", "0");
                    showResultPopUpDiv("ajaxResultWrapperDiv", "Action was Successful!");
                }
            }
            else {
                $('#resultSpan').append($("<ul id='errorMsg' style='list-style: none;' />").append(result.ResultMessage)).addClass("AjaxErrorText");
                $('#errorMsg').css("padding-left", "0");
                showResultPopUpDiv("ajaxResultWrapperDiv", "Ooops! There was an Error");
            }
        }
    });
    return false;
}

被调用的控制器操作在这里:

[HttpPost]
public JsonResult Search(SearchUsersViewModel model) {
    try {
        if (model.SearchFilterType == SearchFilterType.ByUserData)
            return SearchForUsersByUserData(model, string.Empty);
        if (model.SearchFilterType == SearchFilterType.ByEntityData)
            return SearchForUsersByEntityData(model, string.Empty);
    }
    catch (Exception ex) {
        ModelState.AddModelError("", ModelStateErrorUtility.WrapResultMessageForList(ex.Message));   
    }
    return Json(new { Success = false, ResultMessage = ModelStateErrorUtility.GetModelStateErrors(ModelState) }, "application/json", JsonRequestBehavior.AllowGet);
}

private JsonResult SearchForUsersByUserData(SearchUsersViewModel model, string resultMessage) {
    if (model.LastName != null || model.Username != null || model.EmailAddress != null) {
        var listOfMatchingUsers = SearchUserService.SearchByUserData(model.LastName, model.Username, model.EmailAddress);
        return PrepareSearchResultsForPartialView(model, listOfMatchingUsers, resultMessage);
    }
    throw new ArgumentNullException("Last Name, Username or Email Address must be entered for search");
}

private JsonResult SearchForUsersByEntityData(SearchUsersViewModel model, string resultMessage) {
    if ((model.EntityTypeID == 1) || (model.EntityTypeID > 0 && model.SearchField != null)) {
        var listOfMatchingUsers = SearchUserService.SearchByEntityData(model.EntityTypeID, model.SearchField);
        return PrepareSearchResultsForPartialView(model, listOfMatchingUsers, resultMessage);
    }
    throw new ArgumentNullException("Entity Type must be entered for search");
}

private JsonResult PrepareSearchResultsForPartialView(SearchUsersViewModel model, ICollection<SearchUserResultsDTO> list, string resultMessage) {
    return Json(new { Success = true, ResultMessage = ModelStateErrorUtility.WrapResultMessageForList(resultMessage), Data = RenderRazorViewToString("SearchResultsPartial", PrepareSearchResultsForModel(list, model)) }, "application/json", JsonRequestBehavior.AllowGet);
}

private static SearchUsersViewModel PrepareSearchResultsForModel(ICollection<SearchUserResultsDTO> listOfMatchingUsers, SearchUsersViewModel model) {
    if (listOfMatchingUsers.Count != 0) {
        model.Users = listOfMatchingUsers.Select(item => new UserEditViewModel(item)).ToList();
    }
    return model;
}

private string RenderRazorViewToString(string viewName, object model) {
    ViewData.Model = model;
    using (var sw = new StringWriter()) {
        var viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
        var viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
        viewResult.View.Render(viewContext, sw);
        viewResult.ViewEngine.ReleaseView(ControllerContext, viewResult.View);
        return sw.GetStringBuilder().ToString();
    }
}

我尝试了什么:

将操作方法​​设置为JsonResult

没有在响应中指定的内容类型,ajax调用contentType:application / json;字符集= UTF-8

  1. IE 8指向登台服务器IIS提示下载文件
  2. IE 9指向登台服务器IIS什么都不做
  3. Chrome指向登台服务器IIS什么都不做
  4. 指向本地网络服务器的Chrome根本不执行任何操作
  5. 应用/ JSON;响应中指定的charset = utf-8,ajax调用中没有内容类型

    1. IE 8指向登台服务器IIS提示下载文件
    2. IE 9指向登台服务器IIS完美无缺
    3. Chrome指向登台服务器IIS完美无缺
    4. 指向本地网络服务器的Chrome工作正常
    5. 此时我有4种方法中有3种效果很好,IE 8很糟糕。所以现在我改变了动作方法的结果。

      将操作方法​​设置为ActionResult

      没有在响应中指定的内容类型,ajax调用contentType:application / json;字符集= UTF-8

      1. IE 8指向登台服务器IIS提示下载文件
      2. IE 9指向登台服务器IIS什么都不做
      3. Chrome指向登台服务器IIS什么都不做
      4. 指向本地网络服务器的Chrome根本不执行任何操作
      5. 此时我认为在ajax调用本身中指定的contentType是BAD。

        应用/ JSON;响应中指定的charset = utf-8,ajax调用中没有内容类型

        1. IE 8指向登台服务器IIS提示下载文件
        2. IE 9指向登台服务器IIS完美无缺
        3. Chrome指向登台服务器IIS完美无缺
        4. 指向本地网络服务器的Chrome工作正常
        5. 我甚至将脚本文件JSON2.js添加到项目中并在视图中引用了脚本,这根本没有做任何事情。

          这里'疯狂的部分,我有另一个控制器设置相同的方式,它构建完全相同的json,唯一的区别是调用ajax调用它的视图略有不同。这是Ajax方法:

          function setApprovalStatus(username, isApproved) {
              $.ajax({
                  url: "/ELMAdmin/SetApprovalStatus/",
                  dataType: "json",
                  cache: false,
                  type: 'POST',
                  data: { username: username, isApproved: isApproved },
                  success: function (result) {
                      showManageUsersSuccessError(result);
                  }
              });
          }
          

          它调用相同的子例程来渲染网格,唯一的区别是返回的数据。所以我从局部视图中删除了所有文本,IE仍然试图下载该文件。我觉得我已经尝试了所有我知道的东西,现在需要一些额外的眼睛来帮助指出我希望是明显的东西。

2 个答案:

答案 0 :(得分:1)

好的,在查看示例并测试后,您需要将此内容类型添加到您的ajax调用中。

$.ajax({
    url: "/ELMAdmin/Search",
    cache: false,
    type: 'POST',
    contentType: "application/x-www-form-urlencoded;charset=utf-8",
    data: { LastName: lastName.value, Username: username.value, EmailAddress: emailAddress.value, SearchFilterType: searchFilterType.value },
    success: function (result) {
        showManageUsersSuccessError(result);
    }
});

注意contentTypeapplication/x-www-form-urlencoded;charset=utf-8。这应该解决IE8的任何问题。

此外,虽然它可能只是示例,但您希望在搜索按钮上的onclick方法中return false,否则它将返回true,然后再发帖。

//Search By User Info
searchByUserBtn.onclick = function (event) {

    entityName.className = "FieldOk";
    entityName.value = "";
    entityName.setAttribute("disabled", "disabled");
    entityTypeID.value = 0;
    entityTypeID.className = "FieldOk";
    entityErrorMsgField.innerHTML = "";
    filterByUserValidation();

    return false;
}

答案 1 :(得分:0)

即使这个问题已经过时了,我还是会添加一个建议,以防其他人使用ASP.NET MVC 3 or 4并遇到此问题。

根据我的经验,当IE尝试将Json响应作为文件下载时,您只需要在视图中添加对jquery.unobtrusive的引用即可。

例如:

@Scripts.Render("~/Scripts/jquery.unobtrusive-ajax.min.js")

一旦到位,IE将不再尝试从JsonResult控制器操作下载json响应。无需更改响应类型等。