使用 HttpClient PostAsync() 调用 SharePoint 会导致禁止响应



我正在尝试将HttpClient PostAsync((请求发送到公司的内部sharepoint站点,但它返回的响应带有禁止的错误。我拥有加载站点所需的所有访问权限,并且还将所需的标头传递给 HttpClient 对象。

这是代码片段。

HttpClient client = new System.Net.Http.HttpClient (new HttpClientHandler { UseDefaultCredentials = true });
client.BaseAddress = new Uri (string.Format (API_URL, p_siteNumber));
client.DefaultRequestHeaders.Accept.Add (new MediaTypeWithQualityHeaderValue (@"application/atom+xml"));
client.DefaultRequestHeaders.TryAddWithoutValidation ("Accept-Encoding", "gzip, deflate");
client.DefaultRequestHeaders.TryAddWithoutValidation ("Accept-Language", "en-US, en;q=0.8, hi;q=0.6");
client.DefaultRequestHeaders.TryAddWithoutValidation ("User-Agent", "Mozilla/5.0 (Windows NT 6.2; WOW64; rv:19.0) Gecko/20100101 Firefox/19.0");
client.DefaultRequestHeaders.TryAddWithoutValidation ("Accept-Charset", "ISO-8859-1");
HttpResponseMessage httpResponse = await client.PostAsync (urlHttpPost, new StringContent (string.Empty));
string response = await httpResponse.Content.ReadAsStringAsync ();

谁能帮我解决这个问题?提前谢谢。

我遇到了同样的问题,我想发送文件和一些字符串内容。

所以下面的代码帮助了我!!

using (var client = new HttpClient())
        {
            //client.DefaultRequestHeaders.Add("User-Agent", "CBS Brightcove API Service");
            string authorization = GenerateBase64();
            client.DefaultRequestHeaders.Add("Authorization", authorization);

            using (var content = new MultipartFormDataContent())
            {
                string fileName = Path.GetFileName(textBox1.Text);
                //Content-Disposition: form-data; name="json"
                var stringContent = new StringContent(InstancePropertyObject);
                stringContent.Headers.Remove("Content-Type");
                stringContent.Headers.Add("Content-Type", "application/json");
                stringContent.Headers.Add("Content-Disposition", "form-data; name="instance"");
                content.Add(stringContent, "instance");
                var fileContent = new ByteArrayContent(filecontent);
                fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
                {
                    FileName = fileName
                };
                content.Add(fileContent);
                var result = client.PostAsync(targetURL, content).Result; 
            }
        }

最新更新