简体   繁体   中英

How to Declare an Empty ClientContext

I am implementing a new authentication method according to the version of SharePoint in my .NET code, which may vary between the URL. However, I am unsure of how to declare an empty ClientContext variable.

Below is my code snippet:

Uri lUri = new Uri(pSiteUrl);

//To declare an empty ClientContext variable here//

if (pSiteUrl.StartsWith(ConfigurationManager.AppSettings["New_URL"]))
{
    ClientContext lClientContext = SPOClientContext.GetAuthenticatedContext(pSiteUrl);
}
else
{
    ClientContext lClientContext = new ClientContext(pSiteUrl);
}

//lClientContext does not exists if it is not initialised outside the if-else statement above
Folder lRootFolder = lClientContext.Web.GetFolderByServerRelativeUrl(lUri.AbsolutePath + pFolderPath);

I am not sure if this will be of any help but I will try to do my best :).

The ClientContext constructor must have some parameter -> Link

So what You could do is just create not initialized ClientContext and then check if it was not null... something like this should do (based on You code example):



    ClientContext lClientContext = null;
    if (pSiteUrl.StartsWith(ConfigurationManager.AppSettings["New_URL"]))
    {
        lClientContext = SPOClientContext.GetAuthenticatedContext(pSiteUrl); // not sure what actually this is??
    }
    else
    {
        lClientContext = new ClientContext(pSiteUrl);
    }

    if (lClientContext != null)
    {
        Folder lRootFolder = lClientContext.Web.GetFolderByServerRelativeUrl(lUri.AbsolutePath + pFolderPath);
        lClientContext.Dispose();
    }

... just please remember that the ClientContext should always be disposed at the end

maybe some cleaner option would be something like this (that way You will not need to think about the Dispose() at the end)



    public void DoSomething()
    {
        string pSiteUrl = "";
        string somePath = "";
        using (var lClientContext = CreateClientContext(pSiteUrl))
        {
            Folder lRootFolder = lClientContext.Web.GetFolderByServerRelativeUrl(somePath);
        }
    }

    private ClientContext CreateClientContext(string uri) =>
        uri.StartsWith(ConfigurationManager.AppSettings["New_URL"]) ? 
            SPOClientContext.GetAuthenticatedContext(uri) : 
            new ClientContext(uri);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM