【发布时间】:2018-10-17 05:59:59
【问题描述】:
我很难理解为什么在使用 httpclient 创建列表项时出现错误 403。我完全控制了列表,但我收到了 403,这非常令人沮丧。我经历了很多解决方案,但没有一个对我有用。
如果我使用对列表的 ajax 调用创建 HTML 页面,我可以从浏览器创建列表项,但是用 c# 编写的相同代码会引发错误 403。
这是我的 C# 测试代码,它抛出 403,响应为
{"error":{"code":"-2130575251, Microsoft.SharePoint.SPException","message":{"lang":"en-US","value":"The security validation for this page is invalid and might be corrupted. Please use your web browser's Back button to try your operation again."}}}
NetworkCredential cred = new NetworkCredential(username, password);
HttpClient client = new HttpClient(new HttpClientHandler() { Credentials = cred })
{
BaseAddress = new Uri(URL)
};
string cmd = "_api/contextinfo";
client.DefaultRequestHeaders.Add("Accept", "application/json;odata=verbose");
client.DefaultRequestHeaders.Add("ContentType", "application/json");
StringContent httpContent = new StringContent("");
var clientresponse = await client.PostAsync(cmd, httpContent);
if (clientresponse.IsSuccessStatusCode)
{
string formdigest = await clientresponse.Content.ReadAsStringAsync();
JToken t = JToken.Parse(formdigest);
string digest = t["d"]["GetContextWebInformation"]["FormDigestValue"].ToString();
string[] digestArray = digest.Split(',');
NetworkCredential cred2 = new NetworkCredential(username, password);
HttpClient client2 = new HttpClient(new HttpClientHandler() { Credentials = cred2 })
{
BaseAddress = new Uri(URL)
};
client2.DefaultRequestHeaders.Add("Accept", "application/json;odata=verbose");
client2.DefaultRequestHeaders.Add("ContentType", "application/json");
client2.DefaultRequestHeaders.Add("X-HTTP-Method", "POST");
client2.DefaultRequestHeaders.Add("X-RequestDigest", digestArray[0].ToString());
string path = SendShipments.ListPath + "_api/Web/Lists/getbytitle("Test")/items";
string content_Post = "{__metadata:{'type':'SP.Data.TestListItem'},Title:'Test'}";
var httpContent_Post = new StringContent(content_Post, Encoding.UTF8, "application/json");
var clientresponse2 = await client2.PostAsync(path, httpContent_Post);
这是我的 ajax 代码,按预期工作
<script>
$.ajax({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('Test')/items",
type: "POST",
headers: {
"accept": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val(),
"content-Type": "application/json;odata=verbose"
},
data: "{__metadata:{'type':'SP.Data.TestListItem'},Title:'Test'}",
/*where Title is column name and you can add more columns by splitting with ,*/
success: function (data) {
console.log(data.d.results);
},
error: function (error) {
alert(JSON.stringify(error));
}
});
</script>
我尝试添加HttpContext.Current.Items["FormDigestValidated"] = true;,但没有成功。
请指教。谢谢
【问题讨论】:
-
为了让 sharepoint api 正常工作,我必须在租户中使用应用程序权限(未委托,即 ui)注册应用程序,并为应用程序上传 X509 证书。然后我需要使用与证书中的公钥关联的私钥来签署 JWT 以获得访问令牌。
标签: c# rest sharepoint-2013 dotnet-httpclient