You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用C#获取DevOps Wiki页面ETag并更新页面内容?

C#实现Azure DevOps Wiki页面更新(PUT请求)

核心要点

更新Azure DevOps Wiki页面的PUT请求必须包含当前页面版本号(乐观锁机制),同时需要正确的身份验证和请求体结构。以下是完整实现步骤和代码:


1. 身份验证配置

使用个人访问令牌(PAT)进行授权,PAT需拥有Wiki编辑权限(如Wiki Contributors角色)。在请求头中添加Authorization: Basic {base64编码的":"+PAT}。

2. 获取页面版本号

更新前必须先通过GET请求获取目标页面的版本号,否则PUT请求会返回409冲突。版本信息在响应体的version.version字段中。

3. 构造并发送PUT请求

PUT请求的URL与GET一致,请求体为JSON格式,包含content(新内容)和version(当前版本号)两个核心字段。


完整C#代码示例

using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;

public class AzureDevOpsWikiUpdater
{
    private readonly HttpClient _httpClient;
    private readonly string _org;
    private readonly string _project;
    private readonly string _wikiId;

    public AzureDevOpsWikiUpdater(string organization, string project, string wikiId, string patToken)
    {
        _org = organization;
        _project = project;
        _wikiId = wikiId;

        _httpClient = new HttpClient();
        // 配置PAT授权头
        var encodedPat = Convert.ToBase64String(Encoding.ASCII.GetBytes($":{patToken}"));
        _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", encodedPat);
    }

    public async Task UpdatePageAsync(string pagePath, string newContent)
    {
        // 步骤1:获取当前页面版本
        var apiUrl = $"https://dev.azure.com/{_org}/{_project}/_apis/wiki/wikis/{_wikiId}/pages?path={Uri.EscapeDataString(pagePath)}&api-version=7.0";
        var getResponse = await _httpClient.GetAsync(apiUrl);
        getResponse.EnsureSuccessStatusCode();

        var pageResponse = await getResponse.Content.ReadAsStringAsync();
        var pageData = JsonConvert.DeserializeObject<WikiPageDto>(pageResponse);

        if (pageData?.Version == null)
            throw new InvalidOperationException("无法获取页面版本信息,更新失败");

        // 步骤2:构造更新请求体
        var updatePayload = new
        {
            content = newContent,
            version = new { version = pageData.Version.Number }
        };
        var payloadJson = JsonConvert.SerializeObject(updatePayload);
        var requestContent = new StringContent(payloadJson, Encoding.UTF8, "application/json");

        // 步骤3:发送PUT请求
        var putResponse = await _httpClient.PutAsync(apiUrl, requestContent);
        putResponse.EnsureSuccessStatusCode();
    }

    // 反序列化用的DTO类
    private class WikiPageDto
    {
        [JsonProperty("version")]
        public WikiVersionDto Version { get; set; }
    }

    private class WikiVersionDto
    {
        [JsonProperty("version")]
        public int Number { get; set; }
    }
}

// 使用示例
// var updater = new AzureDevOpsWikiUpdater("your-company", "your-project", "wiki-id", "your-pat");
// await updater.UpdatePageAsync("/Home/App-Versions", "### 最新版本\n- v2.0.1 发布于2024-05-20");

注意事项

  • 确保PAT拥有Wiki编辑权限,否则会返回403 Forbidden
  • 页面路径需使用Uri.EscapeDataString处理特殊字符(如空格、斜杠)
  • 版本号必须与当前页面一致,避免并发更新冲突
  • 如果目标页面不存在,PUT请求会自动创建该页面(若需仅更新已存在页面,可先判断页面是否存在)

内容的提问来源于stack exchange,提问作者Bert Otte

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 11:03:30