0
votes

I want to search sharepoint document using C# api call.

I am trying below code:

 string URL = "http://server/_api/search/query?query_parameter=value&query_parameter=value";

            System.Net.Http.HttpClient client = new HttpClient();
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes(string.Format("{0}:{1}", "XXXXX", "XXXXXX"))));
            using (client)
            {
                HttpResponseMessage httpResponseMessage = await client.GetAsync(URL);
                HttpResponseMessage responsemMsgx = httpResponseMessage;
                if (responsemMsgx.IsSuccessStatusCode)
                {
                }
            }

But,i am have a doubt regarding URL below: string URL = "http://server/_api/search/query?query_parameter=value&query_parameter=value";

Please help me with the sharepoint server and constructing the URL. My expected output is something like JSON .

1
& is an XML-encoded ampersand and is extremely unusual to put that in a URL, where an ampersand is not a metacharacter. And then your link doesn't do that so I have no idea what you are trying to do.Dour High Arch

1 Answers

0
votes

If you want to search documents, we can use the Search REST API below to achieve it.

/_api/search/query?querytext='IsDocument:True'

C# example:

string siteUrl = "http://sp2013/sites/team";
string searchQuery = "/_api/search/query?querytext='IsDocument:True'";//search all documents
var credential = new System.Net.NetworkCredential("username", "password", "domainname");

HttpClientHandler handler = new HttpClientHandler() { Credentials = credential };


HttpClient client = new HttpClient(handler);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Add("Accept", "application/json;odata=verbose");
client.DefaultRequestHeaders.Add("ContentType", "application/json;odata=verbose");

var result = client.GetAsync(siteUrl+searchQuery).Result;
var content = result.Content.ReadAsStringAsync().Result;
JObject jobj = JObject.Parse(content);
JArray jarr = (JArray)jobj["d"]["query"]["PrimaryQueryResult"]["RelevantResults"]["Table"]["Rows"]["results"];
foreach (JObject j in jarr)
{
    JArray results = (JArray)j["Cells"]["results"];
    var title = "";
    var path = "";
    foreach (JObject r in results)
    {
        if (r["Key"] != null) 
        {
            if (r["Key"].ToString() == "Title")
            {
                title = r["Value"].ToString();
            }
            if (r["Key"].ToString() == "Path")
            {
                path = r["Value"].ToString();
            }
        }                   
    }
    Console.WriteLine(title + "|" + path);
}