Извлечение данных из списка в приложении, размещенном у поставщика SharePoint 2013

Я разработал приложение, размещенное у поставщика, в SharePoint 2013. Как вы уже знаете, Visual Studio создает веб-приложение и приложение SharePoint. Веб-приложение размещается внутри IIS и приложения SharePoint в семействе веб-сайтов SharePoint. Я пытаюсь получить данные из списка, размещенного в SharePoint, с помощью CSOM. Но я получаю ошибку небезопасного содержимого.

«[заблокировано] Страница в 'https://localhost:44302/Pages/Default.aspx?SPHostUrl=http%3A%2F%2Fecontent&0319c41%2Eecontent%2Eelibrary%2Eapps%2Elocal%2FSharePointApp2%5Fsingeltest' была загружена через HTTPS, но содержала небезопасный контент из 'http://apps-892db5a0319c41.econtent.elibrary.apps.local/sharepointapp2_singeltest/_layouts/15/AppWebProxy.aspx': этот контент также должен быть загружен через HTTPS".

вот мой код в Default.aspx

<script type="text/javascript" src="../Scripts/jquery-1.8.2.js"></script>
<script type="text/javascript" src="../Scripts/MicrosoftAjax.js"></script>
<script type="text/javascript" src="../Scripts/SP.Core.js"></script>
<script type="text/javascript" src="../Scripts/INIT.JS"></script>
<script type="text/javascript" src="../Scripts/SP.Runtime.js"></script>
<script type="text/javascript" src="../Scripts/SP.js"></script>
<script type="text/javascript" src="../Scripts/SP.RequestExecutor.js"></script>

<script type="text/javascript" src="../Scripts/App.js"></script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>

    <form id="form1" runat="server">
    <div>
        <input id="Button1" type="button" value="Get title via CSOM" onclick="execCSOMTitleRequest()" /> <br />
        <input id="Button2" type="button" value="Get Lists via CSOM" onclick="execCSOMListRequest()" />
    </div>
        <p ID="lblResultTitle"></p><br />
        <p ID="lblResultLists"></p>
    </form>
</body>
</html>

и App.js:

var hostwebUrl;
var appwebUrl;

// Load the required SharePoint libraries
$(document).ready(function () {
    //Get the URI decoded URLs.
    hostwebUrl =
        decodeURIComponent(
            getQueryStringParameter("SPHostUrl")
    );
    appwebUrl =
        decodeURIComponent(
            getQueryStringParameter("SPAppWebUrl")
    );

    // resources are in URLs in the form:
    // web_url/_layouts/15/resource
    var scriptbase = hostwebUrl + "/_layouts/15/";

    // Load the js files and continue to the successHandler
    //$.getScript(scriptbase + "/MicrosoftAjax.js",
    //   function () {
    //       $.getScript(scriptbase + "SP.Core.js",
    //           function () {
    //               $.getScript(scriptbase + "INIT.JS",
    //                   function () {
    //                       $.getScript(scriptbase + "SP.Runtime.js",
    //                           function () {
    //                               $.getScript(scriptbase + "SP.js",
    //                                   function () { $.getScript(scriptbase + "SP.RequestExecutor.js", execCrossDomainRequest); }
    //                                   );
    //                           }
    //                           );
    //                   });
    //           });
    //   });
});

function execCrossDomainRequest() {
    alert("scripts loaded");
}
function getQueryStringParameter(paramToRetrieve) {
    var params = document.URL.split("?")[1].split("&");
    var strParams = "";
    for (var i = 0; i < params.length; i = i + 1) {
        var singleParam = params[i].split("=");
        if (singleParam[0] == paramToRetrieve)
            return singleParam[1];
    }
}

function execCSOMTitleRequest() {
    var context;
    var factory;
    var appContextSite;
    var collList;
    //Get the client context of the AppWebUrl
    context = new SP.ClientContext(appwebUrl);
    //Get the ProxyWebRequestExecutorFactory
    factory = new SP.ProxyWebRequestExecutorFactory(appwebUrl);
    //Assign the factory to the client context.
    context.set_webRequestExecutorFactory(factory);
    //Get the app context of the Host Web using the client context of the Application.
    appContextSite = new SP.AppContextSite(context, hostwebUrl);
    //Get the Web
    this.web = context.get_web();
    //Load Web.
    context.load(this.web);
    context.executeQueryAsync(
        Function.createDelegate(this, successTitleHandlerCSOM),
        Function.createDelegate(this, errorTitleHandlerCSOM)
        );
    //success Title
    function successTitleHandlerCSOM(data) {
        $('#lblResultTitle').html("<b>Via CSOM the title is:</b> " + this.web.get_title());
    }
    //Error Title
    function errorTitleHandlerCSOM(data, errorCode, errorMessage) {
        $('#lblResultLists').html("Could not complete CSOM call: " + errorMessage);
    }
}

function execCSOMListRequest() {
    var context;
    var factory;
    var appContextSite;
    var collList;
    //Get the client context of the AppWebUrl
    context = new SP.ClientContext(appwebUrl);
    //Get the ProxyWebRequestExecutorFactory
    factory = new SP.ProxyWebRequestExecutorFactory(appwebUrl);
    //Assign the factory to the client context.
    context.set_webRequestExecutorFactory(factory);
    //Get the app context of the Host Web using the client context of the Application.
    appContextSite = new SP.AppContextSite(context, hostwebUrl);
    //Get the Web
    this.web = context.get_web();
    // Get the Web lists.
    collList = this.web.get_lists();
    //Load Lists.
    context.load(collList);
    context.executeQueryAsync(
        Function.createDelegate(this, successListHandlerCSOM),
        Function.createDelegate(this, errorListHandlerCSOM)
        );
    //Success Lists
    function successListHandlerCSOM() {
        var listEnumerator = collList.getEnumerator();
        $('#lblResultLists').html("<b>Via CSOM the lists are:</b><br/>");
        while (listEnumerator.moveNext()) {
            var oList = listEnumerator.get_current();
            $('#lblResultLists').append(oList.get_title() + " (" + oList.get_itemCount() + ")<br/>");
        }
    }
    //Error Lists
    function errorListHandlerCSOM(data, errorCode, errorMessage) {
        $('#lblResultLists').html("Could not complete CSOM Call: " + errorMessage);
    }
};

Любое решение приветствуется.


person Mohamed Samir    schedule 18.03.2014    source источник
comment
да, я столкнулся с той же проблемой с проблемой межсайтового домена. Я тестирую свой с сайта разработчика o365. Я буду следить за этой веткой или постить разрешение, если получу его.   -  person GoldBishop    schedule 22.03.2014
comment
ваш Default.aspx размещен в приложении или в веб-приложении?   -  person Alex    schedule 21.05.2015


Ответы (1)


ну, во-первых, я могу сказать вам, что ваша логика decodeURIComponent не работает.

Ваш:https://localhost:44302/Pages/Default.aspx?SPHostUrl=http%3A%2F%2Fecontent&0319c41%2Eecontent%2Eelibrary%2Eapps%2Elocal%2FSharePointApp2%5Fsingeltest

Мой: https://localhost:44302/Pages/Default.aspx?SPHostUrl=http://econtent&0319c41.econtent.elibrary.apps.local/SharePointApp2_singeltest

Во-вторых, должен ли контент HostURL быть небезопасным? Если это так, то вы можете изменить настройки браузера. Если нет, то вам нужно понять, почему ваш HostURL находится в анонимной зоне, а AppURL — в безопасной зоне.

В любом случае убедитесь, что у всех есть как минимум доступ для чтения к расположению, из которого вы пытаетесь извлечь данные.

Последнее, что нужно сделать, это настроить расположение доверенного хоста, если у вас есть доступ к центру администрирования.

Вот фрагмент кода для того, что я использовал для тестирования:

    $(document).ready(function () {
    $.getScript(qsHostUrl + "/_layouts/15/SP.RequestExecutor.js", getHostInfo);

    function getHostInfo() {

        var ctxApp = new SP.ClientContext(qsAppUrl);
        var factory = new SP.ProxyWebRequestExecutorFactory(qsAppUrl);
        ctxApp.set_webRequestExecutorFactory(factory);
        var ctxHost = new SP.AppContextSite(ctxApp, qsHostUrl);
        var web = ctxHost.get_web();
        ctxApp.load(web);

        ctxApp.executeQueryAsync(
            Function.createDelegate(this, getHostInfoSuccess),
            Function.createDelegate(this, getHostInfoError)
        );

        function getHostInfoSuccess(sender, args) {
            lblData.html(
                'Title: ' + web.get_title() + '<br/>' +
                'Description: ' + web.get_description()
            );
        }
        function getHostInfoError(sender, args) {
            lblData.html(
                'Request Failed: ' + args.get_message() + '\n' +
                'Stacktrace: ' + args.get_stackTrace()
            );
        }
    }
}
person GoldBishop    schedule 25.03.2014