从sharepoint rest服务下载文件

时间:2014-05-21 17:01:53

标签: sharepoint windows-store-apps

当我尝试使用以下代码使用rest服务从sharepoint站点下载文件时 我得到远程服务器返回403禁止 - 请帮助

String fileurl = "exact sharepoint file url";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(fileurl);
            NetworkCredential credential = new NetworkCredential("username", "password","domain");
            //request.Credentials = credential;
            //request.ContinueTimeout = 10000;
            request.Credentials = credential;


            request.Headers["UserAgent"] = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/533.4 (KHTML, like Gecko) Chrome/5.0.375.99 Safari/533.4";
            request.Accept = "/";
            // request.Headers["Accept"] = "/";

            WebResponse resp = await request.GetResponseAsync();

3 个答案:

答案 0 :(得分:1)

为了能够使用CSOM或REST从SharePoint Online / Office 365下载文件,必须执行身份验证。

关于SharePoint Online身份验证

由于SharePoint Online(SPO)使用基于声明的身份验证,因此您可以考虑以下选项:

使用.NET

使用SharePoint REST服务

为了使用.NET来使用SharePoint REST服务,您可以考虑以下方法:

  • HttpClient - 提供一个基类,用于发送HTTP请求并从URI标识的资源接收HTTP响应。 (.NET Framework 4.5
  • WebClient - 提供向URI标识的资源发送数据和从中接收数据的常用方法。 (.NET Framework 1.1
  • HttpWebRequest - 提供特定于HTTP的WebRequest类实现,比之前的实现更低级(.NET Framework 1.1

所有这些都允许从SharePoint Online下载文件。

实施例

示例1.如何使用SharePointOnlineCredentials类指定SPO凭据

var request = (HttpWebRequest)WebRequest.Create(endpointUri);
request.Credentials = new SharePointOnlineCredentials(username, securedPassword);
//...

示例2.如何使用MsOnlineClaimsHelper class指定SPO身份验证Cookie:

var claimshelper = new MsOnlineClaimsHelper(webUri, userName, password);
var endpointUri = new Uri(webUri,string.Format("/_api/web/getfilebyserverrelativeurl('{0}')/$value", fileUrl));
var request = (HttpWebRequest)WebRequest.Create(endpointUri);
request.Headers.Add("X-FORMS_BASED_AUTH_ACCEPTED", "f");
request.Method = "GET";
request.CookieContainer = claimshelper.CookieContainer;
//...

关键点:

  • SharePoint Auth Cookie通过CookieContainer属性
  • 传递
  • 根据Files and folders REST API reference以下内容 endpoint用于检索文件内容:<app web url>/_api//web/getfilebyserverrelativeurl('<file url>')/$value

答案 1 :(得分:0)

试试这个:

using System.Net;
using (WebClient webClient = new WebClient ())
{
    webClient.DownloadFile(fileurl , filename);
}

答案 2 :(得分:0)

试试这个。让我知道它会起作用吗?

HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK);               
response.Content = new StreamContent(new FileStream(HttpContext.Current.Server.MapPath("~/Documents/" + documentFileName.Name), FileMode.Open, FileAccess.Read));
response.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
response.Content.Headers.ContentDisposition.FileName = documentFileName.Name;
response;