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

.Net Core Word Web Office加载项Ajax调用Web API无预期结果

解决Office加载项Ajax调用Web API返回异常的问题

核心问题分析

  • 你使用了dataType: "JSONP",但后端Web API返回的是纯JSON格式,并非JSONP要求的回调函数包裹格式,导致jQuery无法正确解析响应,触发error回调(尽管HTTP状态码是200)。
  • Word.run的异步处理逻辑有误:Ajax是异步操作,return context.sync()放在success回调里无法被Word.run的Promise链正确捕获,可能导致上下文同步不生效。

具体修复方案

方案1:改用CORS替代JSONP(推荐)

若API与Office加载项存在跨域问题,优先配置CORS而非JSONP:

  1. 后端配置CORS:
    在ASP.NET Core项目的Program.cs中添加CORS中间件:

    builder.Services.AddCors(options =>
    {
        options.AddPolicy("AllowOfficeAddIn",
            policy => policy.WithOrigins("你的Office加载项域名") // 示例:https://localhost:3000
                            .AllowAnyHeader()
                            .AllowAnyMethod());
    });
    
    // 在app.UseRouting()之后添加
    app.UseCors("AllowOfficeAddIn");
    

    后端API方法无需修改,保持原有纯JSON返回即可。

  2. 前端修改Ajax配置:
    移除dataType: "JSONP",改用默认JSON解析,同时用Promise包裹Ajax以适配Word.run的异步逻辑:

    function makeAjaxCall() {
        Word.run(function (context) {
            return new Promise((resolve, reject) => {
                $.ajax({
                    type: 'GET',
                    url: 'https://localhost:7200/api/GetDocuments',
                    dataType: "json",
                    success: function (response) {
                        var doc = context.document.body;
                        doc.insertText(JSON.stringify(response), Word.InsertLocation.start);
                        showNotification("Success", JSON.stringify(response));
                        resolve(context.sync());
                    },
                    error: function (error) {
                        showNotification("error", JSON.stringify(error));
                        reject(error);
                    }
                });
            });
        })
        .catch(errorHandler);
    }
    

方案2:修改后端支持JSONP(仅当无法使用CORS时)

若必须使用JSONP,需让后端返回符合格式的响应:

  1. 修改后端API方法:

    [HttpGet]
    public IActionResult GetDocuments(string callback)
    {
        List<DocumentLibrary> list = _context.DocumentLibraries.ToList();
        // 存在callback参数时返回JSONP格式,否则返回纯JSON
        if (!string.IsNullOrEmpty(callback))
        {
            return Content($"{callback}({JsonSerializer.Serialize(list)})", "application/javascript");
        }
        return new JsonResult(list);
    }
    
  2. 前端保持JSONP配置:
    jQuery会自动添加callback请求参数,后端接收后返回对应包裹格式即可,同时同步调整Word.run的异步逻辑同方案1。

额外注意事项

  • 确保Office加载项的域名已被纳入CORS允许列表(Origin配置需准确)。
  • 直接在浏览器访问https://localhost:7200/api/GetDocuments,确认API返回的是正确的JSON数组。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 01:45:40