April 15, 2015

The remote server returned an error: (403) Forbidden while Connecting to SharePoint site with Managed CSOM

While I was working with my site with Managed CSOM got below error.


System.Net.WebException: The remote server returned an error: (403) Forbidden.at System.Net.HttpWebRequest.GetResponse()at Microsoft.SharePoint.Client.SPWebRequestExecutor.Execute()at Microsoft.SharePoint.Client.ClientContext.GetFormDigestInfoPrivate()at Microsoft.SharePoint.Client.ClientContext.EnsureFormDigest()at Microsoft.SharePoint.Client.ClientContext.ExecuteQuery()at SharePointConsoleApplication1.Program.ConnectSharePoint() in c:\Vinay\Projects\SharePointConsoleApplication1\SharePointConsoleApplication1\Program.cs:line56at SharePointConsoleApplication1.Program.Main(String[] args) in c:\Vinay\Projects\SharePointConsoleApplication1\SharePointConsoleApplication1\Program.cs:line31

This looks strange. After doing some research on Google I got the below solution.

private static void ConnectSharePoint()
{
    try
    {
        using (ClientContext clientContext = new ClientContext(""))
        {
           clientContext.ExecutingWebRequest += clientContext_ExecutingWebRequest;
           List list = clientContext.Web.Lists.GetByTitle("");
           clientContext.Load(list);
           clientContext.ExecuteQuery();
           Console.WriteLine("Connected");
        }
    }
    catch
    {        throw;    }
}

static void clientContext_ExecutingWebRequest(object sender, WebRequestEventArgs e)
{
    try
    {
        e.WebRequestExecutor.WebRequest.Headers.Add("X-FORMS_BASED_AUTH_ACCEPTED", "f");
    }
    catch
    {        throw;    }

}

Hope this solution will help you and save time.