2

Now I have tried to retrieve data from a SharePoint 2013 list, but despite a lot of evidence, there is nothing that really works well.

My question is very simple! How do I write a header that works every time? I shall use the domain, username and password for authentication. I have tried a lot, I put in the code below, so maybe you can see what I'm missing.

I can make all calls from a browser or a REST client without problems.

public void TestRestSP2013(string accessToken)
        {
            HttpWebRequest endpointRequest = (HttpWebRequest)HttpWebRequest.Create(
             "http://<site url>/_vti_bin/client.svc/web/lists/getbytitle('TestList')/Items");
            endpointRequest.Method = "GET";
            endpointRequest.Accept = "application/json;odata=verbose";
            endpointRequest.Headers.Add("Authorization", "Bearer " + accessToken);

            HttpWebResponse endpointResponse = (HttpWebResponse)endpointRequest.GetResponse();
        }

This would I prefer to write, but how I write, Token with domain username and password?

This way I get 401UNAUTHORIZED

public void Aut1()
        {
            const string format0 = @"{0}\{1}";
            const string format1 = @"{0}:{1}";
            string userName = string.Format(format0, domain, user);
            string userandpassword = Convert.ToBase64String(Encoding.Default.GetBytes(string.Format(format1, userName, password)));

            HttpClient _Client = new System.Net.Http.HttpClient();
            _Client.DefaultRequestHeaders.Accept.Clear();
            _Client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            _Client.BaseAddress = new Uri(apiBaseUri);
            _Client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", userandpassword);
            // _Client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", userandpassword);
            var res = _Client.GetAsync("/_api/lists");//.ConfigureAwait(false);
            var test = res.Result;
            outPut = test.ToString();
        }

This way, I get an XML output, but what is it that you have to write - (query=@v1)?@v1={'ViewXml':''} and what should you write when you have to have attachments and people groups.

public string GetDigets()
        {
            String retVal = "";
            try
            {
                string url = apiBaseUri;
                HttpClient client = new HttpClient(new HttpClientHandler() { Credentials = new NetworkCredential(user, password, domain) });
                client.BaseAddress = new System.Uri(url);
                string cmd = "_api/contextinfo";
                client.DefaultRequestHeaders.Add("Accept", "application/json;odata=verbose");
                client.DefaultRequestHeaders.Add("ContentType", "application/json");
                client.DefaultRequestHeaders.Add("ContentLength", "0");
                StringContent httpContent = new StringContent("");
                var response = client.PostAsync(cmd, httpContent).Result;
                if (response.IsSuccessStatusCode)
                {
                    string content = response.Content.ReadAsStringAsync().Result;

                    JObject v = JObject.Parse(content);
                    //dynamic val = JValue.Parse(content);
                    var d = v.SelectToken("d");

                    //JObject val = JValue.Parse(content).ToObject()

                    JObject wi = d.SelectToken("GetContextWebInformation") as JObject;
                    retVal = wi.GetValue("FormDigestValue").ToString();
                }
            }
            catch
            { }
            return retVal;
        }

// Get the list

public async Task GetItems()
            {
                 _token = GetDigets();
                string digest = _token;
                string tempVal = "Error ";
                try
                {
                    string url = apiBaseUri;
                    HttpClient client = new HttpClient(new HttpClientHandler()
                    {
                        Credentials = new NetworkCredential(user, password, domain)
                    });
                    client.BaseAddress = new System.Uri(url);
                    client.DefaultRequestHeaders.Clear();
                    client.DefaultRequestHeaders.Add("Accept", "application/json;odata=verbose");
                    client.DefaultRequestHeaders.Add("ContentType", "application/json;odata=verbose");
                    client.DefaultRequestHeaders.Add("X-RequestDigest", digest);
                    client.DefaultRequestHeaders.Add("X-HTTP-Method", "POST");
                    StringContent strContent = new StringContent("");
                    HttpResponseMessage response = new HttpResponseMessage();

                response = await client.PostAsync("_api/web/lists/getbytitle('test')/GetItems(query=@v1)?@v1={'ViewXml':''}", strContent);
               // response = await client.PostAsync("_api/lists/getbytitle('Pharmakonlist')/items", strContent); This dont work

                response.EnsureSuccessStatusCode();
                if (response.IsSuccessStatusCode)
                {
                    var content = response.Content.ReadAsStringAsync();
                    string test = content.Result.ToString(); // This is XML
                   // var d = JObject.Parse(content.Result);
                    //JObject results = d.SelectTokens("d");
                   // string content = response.Content.ReadAsStringAsync().Result;
                    // JObject val = JToken.Parse(content).ToObject();
                    //JObject d = val.GetValue("d");                   
                }
            }
            catch (Exception ex)
            { string Tempmessage = ex.Message; }
            outPut = tempVal;
            // return tempVal;
        }

This way also gives 401 UNAUTHORIZED

private static async Task<string> GetAPIToken(string userName, string password, string apiBaseUri)
            {
                using (var client = new HttpClient())
                {
                    //setup client
                    client.BaseAddress = new Uri(apiBaseUri);
                    client.DefaultRequestHeaders.Accept.Clear();
                    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                    //setup login data
                    var formContent = new FormUrlEncodedContent(new[]
                    {
                        new KeyValuePair<string, string>("grant_type", "password"),
                        new KeyValuePair<string, string>("username", userName),
                        new KeyValuePair<string, string>("password", password),
                    });
                    //send request
                    HttpResponseMessage responseMessage = await client.PostAsync("/Token", formContent);

                    //get access token from response body
                    var responseJson = await responseMessage.Content.ReadAsStringAsync();
                    var jObject = JObject.Parse(responseJson);
                    return jObject.GetValue("access_token").ToString();
                }
            }

This article was good but SharePointOnlineCredentials - username is an e-mail and not domain \ username [Make a RESTful API Call to SharePoint Online from Console program

Hope you can help. Christian.

  • Is your target site collection in SharePoint Online or on premise? Also, with c# things become so easy if you use managed CSOM instead of REST to talk to SharePoint – Unnie Nov 7 '16 at 10:07
  • HI @Unnie It is a on premise, and it does not matter which method is used. I just need to get data into the program, with no direct connection to SharePoint. – LuckyLyck Nov 7 '16 at 15:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.