从Console App获取SharePoint站点的标题

时间:2018-06-09 11:26:49

标签: c# sharepoint sharepoint-online

我有一个用C#编写的控制台应用程序。我需要从SharePoint站点获取一些信息。此SharePoint实例是Office 365(即SharePoint Online)的一部分。

我的挑战是,我无法使用帮助程序库。我必须使用基于REST的API,因为我使用的是.NET Core。

首先,我使用Azure Active Directory注册了我的控制台应用程序。此控制台应用程序是在我的Office 365环境所属的同一Azure Active Directory中创建的。我还将“Office 365 SharePoint Online”API的“读取所有网站集中的项目”权限授予了我的控制台应用程序。

在我的情况下,我有一个控制台应用程序坐在服务器上。我在SharePoint租户上设置了一个用户名/密码的测试用户。我还拥有我在Azure Active Directory中注册的控制台应用程序的客户端ID和重定向URL。

目前,我有一些代码如下:

var accessToken = await GetToken(); // retrieves a token from Active Directory
using(var client = new HttpClient()) {
    client
        .DefaultRequestHeaders
        .Clear();

    client
        .DefaultRequestHeaders
        .Authorization = new AuthenticationHeaderValue("Bearer", accessToken);

    client
        .DefaultRequestHeaders
        .Accept
        .Add(new MediaTypeWithQualityHeaderValue("application/json"));

    var apiUrl = "https://[mySite].sharepoint.com/_api/web";

    // how do I get the title of the site at the apiUrl variable?
}

我觉得我很接近,因为我正在获取访问令牌。我似乎无法弄清楚如何获得该网站的标题。如何从我的C#代码中获取SharePoint站点的标题?

3 个答案:

答案 0 :(得分:2)

SharePoint REST API的web resource包含一个代表网站标题的Title属性。

通话:

GET http://<site url>/_api/web/title

返回:

<d:Title xmlns:d="http://schemas.microsoft.com/ado/2007/08/dataservices" 
    xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata" 
    xmlns:georss="http://www.georss.org/georss" 
    xmlns:gml="http://www.opengis.net/gml">Site Title Goes Here</d:Title>

或者,假设您已将Accept标题设置为application/json

{
  "odata.metadata": 
  "https://microsoft.sharepoint.com/sites/msw/_api/$metadata#Edm.String",
  "value": "MSW"
}

答案 1 :(得分:1)

刚刚意识到您使用的是SharePoint API而不是Graph API,但它仍然可能对您有用!

这是JSON设置,您不需要它,但它会使反序列化更容易

nvm

反序列化返回的JSON的代码

public class SharePointSiteObject
{
    [JsonProperty("createdDateTime")]
    public string CreatedDate { get; set; }

    [JsonProperty("description")]
    public string Description { get; set; }

    [JsonProperty("id")]
    public string ID { get; set; }

    [JsonProperty("lastModifiedDateTime")]
    public string LastModified { get; set; }

    [JsonProperty("name")]
    public string Name { get; set; }

    [JsonProperty("webUrl")]
    public string WebUrl { get; set; }

    [JsonProperty("displayName")]
    public string DisplayName { get; set; }

    [JsonProperty("createdBy")]
    public user CreatedBy { get; set; }

    [JsonProperty("lastModifiedBy")]
    public user ModifiedBy { get; set; }
}

查询Graph API的通用方法,为其提供端点和令牌

public static SharePointSiteObject SharePointDeserialize(string jObject)
{
    SharePointSiteObject sharePointSite;

    sharePointSite = JsonConvert.DeserializeObject<SharePointSiteObject>(jObject);

    return sharePointSite;
}

使用以下代码调用图API并显示SharePoint网站名称

public static async Task<string> Run(string url, string token)
{

    var httpClient = new HttpClient();
    HttpResponseMessage response;
    try {
        var request = new HttpRequestMessage(HttpMethod.Get, url);
        request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
        response = await httpClient.SendAsync(request);
        var content = await response.Content.ReadAsStringAsync();
        return content;
    }
    catch (Exception ex) {
        return ex.ToString();
    }
}

您应该试用MS Graph Explorer,它非常实用:https://developer.microsoft.com/en-us/graph/graph-explorer

答案 2 :(得分:1)

SharePoint端点遵循OData约定。

因此,您可以使用$select查询选项来指定给定网络或列表或字段等所需的数据。

因此,在您的情况下,您可以简单地修改您的端点,如下所示:

var apiUrl = "https://[mySite].sharepoint.com/_api/web?$select=Title";

如果您希望获得其他属性,如说明,徽标,Webtemplate等,您可以将其附加为:

var apiUrl = "https://[mySite].sharepoint.com/_api/web?$select=Title,Description,
SiteLogoUrl,WebTemplate";

参考 - List of properties in SPO - Web object

另外,请确保您在Have full control of all site collections权限中选中Office 365 SharePoint Online权限,如下所示:

enter image description here

我正在使用的富勒版代码:

1)创建AuthenticationResponse.cs类:

public class AuthenticationResponse
{
        public string token_type { get; set; }
        public string scope { get; set; }
        public int expires_in { get; set; }
        public int expires_on { get; set; }
        public int not_before { get; set; }
        public string resource { get; set; }
        public string access_token { get; set; }
        public string refresh_token { get; set; }
        public string id_token { get; set; }
}

2)在您的代码中使用它,如下所示:

string userName = "user@tenantName.onmicrosoft.com";
string password = "password";

List<KeyValuePair<string, string>> vals = new List<KeyValuePair<string, string>>();

string tenantName = "tenantName.OnMicrosoft.com";
string authString = "https://login.microsoftonline.com/" + tenantName;
string resource = "https://graph.microsoft.com";

AuthenticationContext authenticationContext = new AuthenticationContext(authString, false);

string clientId = "<client-id>";
string key = "<client-secret>";

vals.Add(new KeyValuePair<string, string>("client_id", clientId));
vals.Add(new KeyValuePair<string, string>("resource", resource));
vals.Add(new KeyValuePair<string, string>("username", userName));
vals.Add(new KeyValuePair<string, string>("password", password));
vals.Add(new KeyValuePair<string, string>("grant_type", "password"));
vals.Add(new KeyValuePair<string, string>("client_secret", key));

string url = string.Format("https://login.windows.net/{0}/oauth2/token", tenantName);

using (HttpClient httpClient = new HttpClient())
{
    httpClient.DefaultRequestHeaders.Add("Cache-Control", "no-cache");
    HttpContent content = new FormUrlEncodedContent(vals);
    HttpResponseMessage hrm = httpClient.PostAsync(url, content).Result;

    AuthenticationResponse authenticationResponse = null;
    if (hrm.IsSuccessStatusCode)
    {
        Stream data = await hrm.Content.ReadAsStreamAsync();
        DataContractJsonSerializer serializer = new
        DataContractJsonSerializer(typeof(AuthenticationResponse));
        authenticationResponse = (AuthenticationResponse)serializer.ReadObject(data);

        var accessToken = authenticationResponse.access_token;

        httpClient
        .DefaultRequestHeaders
        .Clear();

        httpClient
            .DefaultRequestHeaders
            .Authorization = new AuthenticationHeaderValue("Bearer", accessToken);

        httpClient
            .DefaultRequestHeaders
            .Accept
            .Add(new MediaTypeWithQualityHeaderValue("application/json"));

        var apiUrl = "https://[mySite].sharepoint.com/_api/web?$select=Title";      

    }
}