If we are using SharePoint app model AutoHosted Environment, we need to use Client Context model to access SharePoint.
Therefore, first you need to get a Valid Access Token from SharePoint Server. For that, you need to pass the SharePoint Site Url (This is available as SPHostUrl
in the Query String) and Context Token that we can generate from passing the request Object.
TokenHelper
class provides methods that can be used to access the SharePoint server and generate Access Tokens.
- Get the Context Token by passing the
HttpRequest
.
String context = TokenHelper.GetContextTokenFromRequest(Request);
- Then get the Uri from the query string which provides the path to SharePoint server.
Uri SharePointUri = new Uri(Request.QueryString["SPHostUrl"]);
- Then validate and generate access Token.
SharePointContextToken contextToken =
TokenHelper.ReadAndValidateContextToken(context, SharePointUri.Authority);
String AcessToken = TokenHelper.GetAccessToken(contextToken, sharepointUrl.Authority).AccessToken;
- Finally, get a
ClientContext
by passing Url
and AccessToken
.
ClientContext ClientC =
TokenHelper.GetClientContextWithAccessToken(sharepointUrl.ToString(), AcessToken);