从控制台应用程序获取 SharePoint 站点的标题
Get Title of SharePoint Site from Console App
我有一个用 C# 编写的控制台应用程序。我需要从 SharePoint 站点获取一些信息。此 SharePoint 实例是 Office 365(即 SharePoint Online)的一部分。
我的挑战是,我无法使用帮助程序库。我必须使用 REST-based APIs,因为我使用的是 .NET Core。
首先,我在 Azure Active Directory 中注册了我的控制台应用程序。此控制台应用程序是在我的 Office 365 环境所属的同一 Azure Active Directory 中创建的。我还向我的控制台应用程序授予了 "Read items in all site collections" 对 "Office 365 SharePoint Online" API 的委派权限。
在我的情况下,我有一个位于服务器上的控制台应用程序。我在我的 SharePoint 租户上设置了一个具有 username/password 的测试用户。我还有在 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 网站的标题?
刚意识到您使用的是 SharePoint API 而不是 Graph API,但它仍然可能对您有用!
这是 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; }
}
反序列化返回的代码JSON
public static SharePointSiteObject SharePointDeserialize(string jObject)
{
SharePointSiteObject sharePointSite;
sharePointSite = JsonConvert.DeserializeObject<SharePointSiteObject>(jObject);
return sharePointSite;
}
查询图形的通用方法API,为其提供端点和令牌
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();
}
}
在要调用图表的地方使用以下代码 API 并显示 SharePoint 站点名称
string url = "https://graph.microsoft.com/v1.0/sites/" + sharePointID;
string token = await GetToken();
var request = await Run(url, token);
var result = SharePointDeserialize(request);
Console.WriteLine(result.DisplayName);
您应该试用 MS Graph Explorer,它非常有用:https://developer.microsoft.com/en-us/graph/graph-explorer
代表网站标题的 SharePoint REST API web
resource includes a Title
属性。
通话中:
GET http://<site url>/_api/web/title
Returns:
<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
header 设置为 application/json
:
{
"odata.metadata":
"https://microsoft.sharepoint.com/sites/msw/_api/$metadata#Edm.String",
"value": "MSW"
}
SharePoint 端点遵循 OData 约定。
因此,您可以使用 $select
查询选项来指定给定网站、列表或字段等所需的数据。
因此,对于您的情况,您可以简单地修改您的端点,如下所示:
var apiUrl = "https://[mySite].sharepoint.com/_api/web?$select=Title";
如果您想获得其他属性,如描述、徽标、Web 模板等,您可以将其附加为:
var apiUrl = "https://[mySite].sharepoint.com/_api/web?$select=Title,Description,
SiteLogoUrl,WebTemplate";
参考 - List of properties in SPO - Web object
此外,请确保您在 Office 365 SharePoint Online
权限中检查了 Have full control of all site collections
权限,如下所示:
我正在使用的代码的完整版本:
1) 创建 AuthenticationResponse.cs
class:
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";
}
}
我有一个用 C# 编写的控制台应用程序。我需要从 SharePoint 站点获取一些信息。此 SharePoint 实例是 Office 365(即 SharePoint Online)的一部分。
我的挑战是,我无法使用帮助程序库。我必须使用 REST-based APIs,因为我使用的是 .NET Core。
首先,我在 Azure Active Directory 中注册了我的控制台应用程序。此控制台应用程序是在我的 Office 365 环境所属的同一 Azure Active Directory 中创建的。我还向我的控制台应用程序授予了 "Read items in all site collections" 对 "Office 365 SharePoint Online" API 的委派权限。
在我的情况下,我有一个位于服务器上的控制台应用程序。我在我的 SharePoint 租户上设置了一个具有 username/password 的测试用户。我还有在 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 网站的标题?
刚意识到您使用的是 SharePoint API 而不是 Graph API,但它仍然可能对您有用!
这是 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; }
}
反序列化返回的代码JSON
public static SharePointSiteObject SharePointDeserialize(string jObject)
{
SharePointSiteObject sharePointSite;
sharePointSite = JsonConvert.DeserializeObject<SharePointSiteObject>(jObject);
return sharePointSite;
}
查询图形的通用方法API,为其提供端点和令牌
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();
}
}
在要调用图表的地方使用以下代码 API 并显示 SharePoint 站点名称
string url = "https://graph.microsoft.com/v1.0/sites/" + sharePointID;
string token = await GetToken();
var request = await Run(url, token);
var result = SharePointDeserialize(request);
Console.WriteLine(result.DisplayName);
您应该试用 MS Graph Explorer,它非常有用:https://developer.microsoft.com/en-us/graph/graph-explorer
代表网站标题的 SharePoint REST API web
resource includes a Title
属性。
通话中:
GET http://<site url>/_api/web/title
Returns:
<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
header 设置为 application/json
:
{
"odata.metadata":
"https://microsoft.sharepoint.com/sites/msw/_api/$metadata#Edm.String",
"value": "MSW"
}
SharePoint 端点遵循 OData 约定。
因此,您可以使用 $select
查询选项来指定给定网站、列表或字段等所需的数据。
因此,对于您的情况,您可以简单地修改您的端点,如下所示:
var apiUrl = "https://[mySite].sharepoint.com/_api/web?$select=Title";
如果您想获得其他属性,如描述、徽标、Web 模板等,您可以将其附加为:
var apiUrl = "https://[mySite].sharepoint.com/_api/web?$select=Title,Description,
SiteLogoUrl,WebTemplate";
参考 - List of properties in SPO - Web object
此外,请确保您在 Office 365 SharePoint Online
权限中检查了 Have full control of all site collections
权限,如下所示:
我正在使用的代码的完整版本:
1) 创建 AuthenticationResponse.cs
class:
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";
}
}