iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🕵️‍♂️

Retrieving Web Requests Executed via CSOM

に公開

CSOM issues HTTP requests internally, and to verify what kind of requests are being sent, you typically need to use tools like Fiddler. However, that can be cumbersome, so I would like to introduce a method to retrieve them directly from your code. The e.WebRequestExecutor.GetRequestStream available in the ExecutingWebRequest event is not readable. Therefore, I am using reflection to retrieve the internal TextReader.

public static class Program
{

    private static void Main(string[] args)
    {
        var url = "{{site-url}}";
        var userName = "{{user-name}}";
        var rawPassword = "{{password}}";
        var securePasseord = new SecureString();
        foreach (var c in rawPassword)
        {
            securePasseord.AppendChar(c);
        }
        using (var ctx = new ClientContext(url))
        {
            ctx.Credentials = new SharePointOnlineCredentials(userName, securePasseord);
            ctx.ExecutingWebRequest += (sender, e) =>
            {
                var clientRequestType = ctx.PendingRequest.GetType();
                var buildQueryMethod = clientRequestType.GetMethod("BuildQuery", BindingFlags.Instance | BindingFlags.NonPublic);
                var chunkStringBuilderObject = buildQueryMethod.Invoke(ctx.PendingRequest, null);
                var chunkStringBuilderType = chunkStringBuilderObject.GetType();
                var createTextReaderMethod = chunkStringBuilderType.GetMethod("CreateTextReader", BindingFlags.Instance | BindingFlags.Public);
                var textReader = createTextReaderMethod.Invoke(chunkStringBuilderObject, null) as TextReader;
                Console.WriteLine(textReader.ReadToEnd());
            };
            var web = ctx.Web;
            ctx.Load(web);
            ctx.ExecuteQuery();
        }
        Console.ReadLine();
    }

}

Running this code will produce the following output:

<Request AddExpandoFieldTypeSuffix="true" SchemaVersion="15.0.0.0" LibraryVersion="16.0.0.0" ApplicationName=".NET Library" xmlns="http://schemas.microsoft.com/sharepoint/clientquery/2009">
    <Actions>
        <ObjectPath Id="2" ObjectPathId="1" />
        <ObjectPath Id="4" ObjectPathId="3" />
        <Query Id="5" ObjectPathId="3">
            <Query SelectAllProperties="true">
                <Properties />
            </Query>
        </Query>
    </Actions>
    <ObjectPaths>
        <StaticProperty Id="1" TypeId="{3747adcd-a3c3-41b9-bfab-4a64dd2f1e0a}" Name="Current" />
        <Property Id="3" ParentId="1" Name="Web" />
    </ObjectPaths>
</Request>

Discussion