如何检查SharePoint URL是否存在?

问题描述 投票:0回答:1

假设我们有以下 SharePoint 工作 URL:

https://mywebsite.sharepoint.com/_layouts/15/Test.aspx

以下代码可用于确定 URL 是否有效,除非用户通过 Azure AD 访问令牌进行身份验证

var request = NetHelper.CreateWebRequest(url,
                    allowAutoRedirect: true,
                    method: WebRequestMethods.Http.Head);
......
// Authentication
......
bool exists = false;
using (var response = request.GetResponseWithRetry())
{
    if (response != null)
    {
        exists = response.StatusCode == HttpStatusCode.OK;
    }
}

当我们有

CookieContainer
(用户名/密码认证)进行身份验证时,此方法有效。但是,根据https://sharepoint.stackexchange.com/questions/248732/how-to-get-cookies-after-obtaining-azure-ad-access-token-to-sharepoint-online/248735这是不可能的为了在使用 Azure AD 身份验证时使
WebRequest
工作,我们应用
HttpRequestHeader.Authorization
标头。

我尝试使用 CSOM 库:

var csomFile = context.Web.GetFileByServerRelativeUrl(serverRelativeUrl);
context.Load(csomFile, f => f.Exists);
context.ExecuteQueryWithRetry();
bool exists = csomFile != null && csomFile.Exists;

但是,这种代码仅适用于实际文件(我猜)。对于 URL

False
,它始终返回
https://mywebsite.sharepoint.com/_layouts/15/Test.aspx

所以,我的问题是 - 有没有办法使用 CSOM 库确定 URL 是否存在,假设我们已经拥有经过身份验证的

ClientContext
对象(可以使用
CookieContainer
HttpRequestHeader.Authorization
标头)。

c# .net sharepoint sharepoint-online csom
1个回答
0
投票

如果 URL 应指向 SharePoint 页面,您可以使用 CSOM 尝试加载该页面的 File 对象,并在 file 不存在时捕获任何异常:

bool pageExists = false;
try
{
    var pageFile = context.Web.GetFileByServerRelativeUrl("/_layouts/15/Test.aspx");
    context.Load(pageFile);
    context.ExecuteQuery(); // Or ExecuteQueryWithRetry as per your utility method
    // If no exception is thrown, the file exists
    pageExists = true;
}
catch (Microsoft.SharePoint.Client.ServerException)
{
    // The file does not exist or some other server error occurred
    pageExists = false;
}

如果没有文件,您可能需要设置一个 httpclient azure AD auth

using (var httpClient = new HttpClient())
{
    httpClient.DefaultRequestHeaders.Authorization = 
        new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", "your_access_token_here");
    try
    {
        var response = await httpClient.GetAsync("https://mywebsite.sharepoint.com/_layouts/15/Test.aspx");
        bool exists = response.IsSuccessStatusCode;
    }
    catch (HttpRequestException)
    {
        // Handle exceptions or assume false if the request failed
    }
}

或者你可以封装一个单独的自定义类来通过http get请求检查url是否存在:

using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;

public class SharePointPageChecker
{
    private readonly HttpClient _httpClient;
    private readonly string _accessToken;

    public SharePointPageChecker(string accessToken)
    {
        _httpClient = new HttpClient();
        _accessToken = accessToken;
    }

    public async Task<bool> CheckPageExistsAsync(string pageUrl)
    {
        // Set the authorization header with the bearer token
        _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", _accessToken);

        try
        {
            // Send a GET request to the page URL
            HttpResponseMessage response = await _httpClient.GetAsync(pageUrl);

            // Check if the request was successful
            return response.IsSuccessStatusCode;
        }
        catch (HttpRequestException e)
        {
            // Log the exception or handle it as needed
            Log.Info($"Error sending request: {e.Message}");
            return false;
        }
    }
}

封装类的使用示例:

var checker = new SharePointPageChecker("your_access_token_here");
bool exists = await checker.CheckPageExistsAsync("https://mywebsite.sharepoint.com/_layouts/15/Test.aspx");
Log.Info($"Page exists: {exists}");

如果您没有实现日志记录,请将 Log.Info() 更改为 Console.WriteLine 或其他内容,以便您可以看到结果

© www.soinside.com 2019 - 2024. All rights reserved.