SharePoint REST API 创建字段并添加至所有内容类型的实现问询
实现方法
你可以通过CreateFieldAsXml的参数直接实现将字段添加到所有内容类型,无需手动逐个绑定:
CSOM 调用方式
FieldCollection.AddFieldAsXml方法通过AddFieldOptions枚举即可控制该行为,示例代码如下:
using Microsoft.SharePoint.Client; string siteUrl = "https://你的租户地址/sites/站点名"; string listTitle = "目标列表名称"; // 替换为你自己的字段Schema定义 string fieldSchema = "<Field Type='Text' DisplayName='自定义字段' Name='CustomField' ID='{新生成的GUID}' Group='自定义列' />"; using (ClientContext ctx = new ClientContext(siteUrl)) { // 按需配置身份验证 ctx.Credentials = new SharePointOnlineCredentials("用户名", "安全字符串密码"); List targetList = ctx.Web.Lists.GetByTitle(listTitle); // AddToAllContentTypes参数即实现添加到所有内容类型 Field newField = targetList.Fields.AddFieldAsXml( fieldSchema, true, AddFieldOptions.AddToAllContentTypes | AddFieldOptions.AddToDefaultView ); ctx.Load(newField); ctx.ExecuteQuery(); }
REST API 调用方式
调用fields端点的createfieldasxml接口时,在请求参数中指定AddToAllContentTypes为true即可:
- 请求地址:
POST https://你的租户地址/sites/站点名/_api/web/lists/getbytitle('目标列表名称')/fields/createfieldasxml - 请求头必填项:
Accept: application/json;odata=verboseContent-Type: application/json;odata=verboseX-RequestDigest: 你获取到的请求摘要值
- 请求体示例:
{ "parameters": { "__metadata": { "type": "SP.XmlSchemaFieldCreationInformation" }, "SchemaXml": "<Field Type='Text' DisplayName='自定义字段' Name='CustomField' Group='自定义列' />", "AddToAllContentTypes": true, "AddToDefaultView": true } }
已创建字段批量绑定方案
如果字段已经创建完成,你可以遍历列表下所有内容类型批量添加字段链接:
using (ClientContext ctx = new ClientContext(siteUrl)) { List targetList = ctx.Web.Lists.GetByTitle(listTitle); Field targetField = targetList.Fields.GetByInternalNameOrTitle("CustomField"); ContentTypeCollection ctCollection = targetList.ContentTypes; ctx.Load(targetField); ctx.Load(ctCollection); ctx.ExecuteQuery(); foreach (ContentType ct in ctCollection) { FieldLinkCreationInformation flInfo = new FieldLinkCreationInformation(); flInfo.Field = targetField; ct.FieldLinks.Add(flInfo); ct.Update(false); } ctx.ExecuteQuery(); }
内容的提问来源于stack exchange,提问作者Ghostmaster
相关产品推荐
相关产品推荐

