Поделиться через


Увеличение максимального размера сообщения

Дата последнего изменения: 1 сентября 2011 г.

Применимо к: SharePoint Foundation 2010

Доступно на сайте SharePoint Online

При выполнении крупного запроса с помощью клиентской объектной модели может возникнуть ошибка запроса. Если это происходит, можно использовать серверную объектную модель для увеличения максимального размера сообщения, который разрешен службой WCF, Client.svc, которая поддерживает клиентскую объектную модель SharePoint Foundation. Другой способ заключается в использовании протокола DAV для запроса PUT.

Серверная объектная модель предоставляет два свойства для увеличения максимального размера сообщения. Можно задать свойство MaxReceivedMessageSize в классе SPWcfServiceSettings или свойство MaxReceivedMessageSize в классе SPClientRequestServiceSettings. Доступ к этим свойствам можно получить с помощью текущего объекта SPWebService одним из следующих способов: SPWebService.ContentService.ClientRequestServiceSettings или SPWebService.ContentService.WcfServiceSettings["Client.svc"]. В зависимости от значения свойства в объекте SPClientRequestServiceSettingsSharePoint Foundation использует или не использует это свойство в объекте SPWcfServiceSettings, как показано далее.

  • Если значение SPWebService.ContentService.ClientRequestServiceSettings.MaxReceivedMessageSize больше нуля, SharePoint Foundation использует это значение как значение свойства.

  • Если значение SPWebService.ContentService.ClientRequestServiceSettings.MaxReceivedMessageSize равно нулю, SharePoint Foundation использует для свойства значение по умолчанию.

  • Если значение SPWebService.ContentService.ClientRequestServiceSettings.MaxReceivedMessageSize равно -1, SharePoint Foundation использует значение SPWcfServiceSettings для свойства, если оно указано. Если значение не указано, SharePoint Foundation использует 64 КБ.

Увеличение параметра MaxReceivedMessageSize службы WCF

В следующем фрагменте показано, как использовать свойство MaxReceivedMessageSize объекта SPClientRequestServiceSettings для изменения размера сообщения.

Public Shared Sub IncreaseMaxReceivedMessageSize()
    Dim contentService As SPWebService = SPWebService.ContentService
    contentService.ClientRequestServiceSettings.MaxReceivedMessageSize = 10485760  ' 10MB
    contentService.Update()
End Sub
public static void IncreaseMaxReceivedMessageSize()
{        
    SPWebService contentService = SPWebService.ContentService;
    contentService.ClientRequestServiceSettings.MaxReceivedMessageSize = 10485760;  // 10MB
    contentService.Update();
}

В следующем фрагменте показано, как использовать свойство MaxReceivedMessageSize объекта SPWcfServiceSettings для изменения параметра. В примере свойству SPClientRequestServiceSettings присваивается значение -1.

Public Shared Sub IncreaseMaxReceivedMessageSize()
    Dim contentService As SPWebService = SPWebService.ContentService
    
    ' Must set this to -1, else, the MaxReceivedMessageSize value for
    ' SPWebService.ContentService.WcfServiceSettings["client.svc"] will not be used.
    contentService.ClientRequestServiceSettings.MaxReceivedMessageSize = -1
    
    ' SPWcfServiceSettings has other Properties that you can set.
    Dim csomWcfSettings As New SPWcfServiceSettings()
    csomWcfSettings.MaxReceivedMessageSize = 10485760  ' 10MB
    contentService.WcfServiceSettings("client.svc") = csomWcfSettings
    
    contentService.Update()
End Sub
public static void IncreaseMaxReceivedMessageSize ()
{
    SPWebService contentService = SPWebService.ContentService;

    /* Must set this to -1, else, the MaxReceivedMessageSize value for
    SPWebService.ContentService.WcfServiceSettings["client.svc"] will not be used.*/
    contentService.ClientRequestServiceSettings.MaxReceivedMessageSize = -1;

    // SPWcfServiceSettings has other Properties that you can set.
    SPWcfServiceSettings csomWcfSettings = new SPWcfServiceSettings();
    csomWcfSettings.MaxReceivedMessageSize = 10485760; // 10MB
    contentService.WcfServiceSettings["client.svc"] = csomWcfSettings;

    contentService.Update();
}

Использование протокола DAV для запроса

В следующем примере показано, как использовать протокол DAV для выполнения запроса.

WebRequest.RegisterPrefix("http://", WebRequestCreator.ClientHttp)

Dim request As HttpWebRequest = DirectCast(WebRequestCreator.ClientHttp.Create(New Uri("https://Server/MyFile.txt")), HttpWebRequest)
request.Method = "PUT"

' Make an asynchronous call for the request stream. The callback method will be called on a background thread. 
Dim asyncResult As IAsyncResult = request.BeginGetRequestStream(New AsyncCallback(RequestStreamCallback), request)

Private Sub RequestStreamCallback(ByVal ar As IAsyncResult)
    Dim request As HttpWebRequest = TryCast(ar.AsyncState, HttpWebRequest)
    Dim requestStream As Stream = request.EndGetRequestStream(ar)
    Dim streamWriter As New StreamWriter(requestStream)
    
    ' Write your file here.
    streamWriter.Write("Hello World!")
    
    ' Close the stream.
    streamWriter.Close()
    
    ' Make an asynchronous call for the response. The callback method will be called on a background thread. 
    
    request.BeginGetResponse(New AsyncCallback(ResponseCallback), request)
End Sub

Private Sub ResponseCallback(ByVal ar As IAsyncResult)
    Dim request As HttpWebRequest = TryCast(ar.AsyncState, HttpWebRequest)
    Dim response As WebResponse = Nothing
    Try
        response = request.EndGetResponse(ar)
    Catch generatedExceptionName As WebException
    Catch generatedExceptionName As SecurityException
        
        ' You may need to analyze the response to see if it succeeded.
    End Try
End Sub
WebRequest.RegisterPrefix("http://", WebRequestCreator.ClientHttp);

HttpWebRequest request = (HttpWebRequest)WebRequestCreator.ClientHttp.Create(new Uri("https://Server/MyFile.txt"));
request.Method = "PUT";

/* Make an asynchronous call for the request stream. The callback method will be called on a background thread. */ 
IAsyncResult asyncResult = request.BeginGetRequestStream(new AsyncCallback(RequestStreamCallback), request);

private void RequestStreamCallback(IAsyncResult ar)
{
    HttpWebRequest request = ar.AsyncState as HttpWebRequest;            
    Stream requestStream = request.EndGetRequestStream(ar);
    StreamWriter streamWriter = new StreamWriter(requestStream);

    // Write your file here.
    streamWriter.Write("Hello World!");            

    // Close the stream.
    streamWriter.Close();

    /* Make an asynchronous call for the response. The callback method will be called on a background thread. */
    request.BeginGetResponse(new AsyncCallback(ResponseCallback), request);
}       

private void ResponseCallback(IAsyncResult ar)
{
    HttpWebRequest request = ar.AsyncState as HttpWebRequest;
    WebResponse response = null;
    try
    {
        response = request.EndGetResponse(ar);
    }
    catch (WebException)
    {}
    catch (SecurityException)
    {}

    // You may need to analyze the response to see if it succeeded.
}

В приложении Silverlight также может потребоваться сформировать XML-файл политики клиентского доступа, как показано в следующем примере. Этот файл можно разместить в каталоге %inetpub%\wwwroot\wss\VirtualDirectories\80.

<?xml version="1.0" encoding="utf-8"?>
<access-policy>
  <cross-domain-access>
    <!--Enables Silverlight 3 all methods functionality-->
    <policy>
      <allow-from http-methods="*">"
        <domain uri="*"/>
      </allow-from>
      <grant-to>
        <resource path="/" include-subpaths="true"/>
      </grant-to>
    </policy>
    <!--Enables Silverlight 2 clients to continue to work normally -->
    <policy>
      <allow-from >
        <domain uri="*"/>
      </allow-from>
      <grant-to>
        <resource path="/" include-subpaths="true"/>
      </grant-to>
    </policy>
  </cross-domain-access>
</access-policy>

Дополнительные сведения о взаимодействии Silverlight и HTTP см. в статье HTTP Communication and Security with Silverlight.

См. также

Концепции

Обзор извлечения данных

Инструкции по использованию клиентской объектной модели

Общие задачи программирования

Другие ресурсы

Использование управляемой клиентской объектной модели SharePoint Foundation 2010

Центр ресурсов объектной модели клиента (Возможно, на английском языке)