Thursday, 29 May 2014

The remote server returned an error: (403) Forbidden

The remote server returned an error: (403) Forbidden
Troubleshooting Exceptions: System.Net.WebException
Root Cause: You might have missing SPO Authentication
Solution:

 Check this method in below code: SPOAuthe
 clientContext = SPOAuthe(clientContext);



using System;
using Microsoft.SharePoint.Client;
using SP = Microsoft.SharePoint.Client;
using System.Security;
namespace Microsoft.SDK.SharePointServices.Samples
{
class RetrieveListItems
{
static void Main()
{
string siteUrl = "http://MyServer/sites/MySiteCollection";
ClientContext clientContext = new ClientContext(siteUrl);
clientContext = SPOAuthe(clientContext);
SP.List oList = clientContext.Web.Lists.GetByTitle("Announcements");
CamlQuery camlQuery = new CamlQuery();
camlQuery.ViewXml = "<View><Query><Where><Geq><FieldRef Name='ID'/>" +
"<Value Type='Number'>10</Value></Geq></Where></Query><RowLimit>100</RowLimit></View>";
ListItemCollection collListItem = oList.GetItems(camlQuery);
clientContext.Load(collListItem);
clientContext.ExecuteQuery();
foreach (ListItem oListItem in collListItem)
{
Console.WriteLine("ID: {0} \nTitle: {1} \nBody: {2}", oListItem.Id, oListItem["Title"], oListItem["Body"]);
}
}
public static ClientContext SPOAuthe(ClientContext ctx)
{
string uname = "MyName";
string pword = "Password";
SecureString objSS = new SecureString();
foreach (char itemC in pword.ToCharArray())
{
objSS.AppendChar(itemC);
}
ctx.Credentials = new SharePointOnlineCredentials(uname, objSS);
return ctx;
}
}
}
view raw gistfile1.cs hosted with ❤ by GitHub
Now your code should work..