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

为何TypeScript代码无法获取C#代码的返回值?

问题:TypeScript通过$.ajax调用C#方法无法获取返回值

我用$.ajax从TypeScript调用C#后端方法,C#方法明明返回了值,但TypeScript端无法获取到,控制台仅输出result from RegionGrowing: ,看不到预期的返回内容。

TypeScript代码

$.ajax({
    type: "POST",
    url: "/ShapeDetection/RegionGrowing",
    data: {
        points: points,
        faces: faces,
        mousex: pointer.x.toString(),
        mousez: pointer.z.toString()
    },
    success: (result) => {
        console.log("result from RegionGrowing: ", result);
    },
    dataType: "json"
});

C#代码

[HttpPost]
public JsonResult RegionGrowing(SimpleShape simpleShape)
{
    return Json("hello world");
}

我原本预期控制台会显示result from RegionGrowing: hello world,但实际没有拿到返回值。


解决办法

1. 修正返回格式与dataType的匹配问题

你设置了dataType: "json",要求后端返回合法的JSON格式,但当前C#返回的是纯字符串"hello world",这不是标准的JSON对象(纯字符串作为JSON需要被双引号包裹,但直接返回字符串的话,后端可能没有正确序列化)。

修改C#代码,返回一个JSON对象:

[HttpPost]
public JsonResult RegionGrowing(SimpleShape simpleShape)
{
    // 返回包含消息的JSON对象
    return Json(new { Message = "hello world" });
}

同时在TypeScript的回调中读取对应属性:

success: (result) => {
    console.log("result from RegionGrowing: ", result.Message);
},

2. 验证模型绑定是否正常

检查SimpleShape类的属性是否和前端传递的points、faces、mousex、mousez参数名称、类型完全匹配。如果模型绑定失败,后端方法可能无法正常执行,导致返回空值或错误。

可以在C#方法中添加断点,查看simpleShape是否正确接收到参数,或者添加日志记录确认方法执行状态。

3. 添加错误回调排查请求问题

在$.ajax中增加error回调,查看请求是否存在错误(比如404、500等状态码),以及响应内容:

$.ajax({
    // 原有配置...
    error: (xhr, status, error) => {
        console.error("请求错误状态:", status);
        console.error("错误信息:", error);
        console.error("后端响应内容:", xhr.responseText);
    }
});

4. .NET版本兼容提示(针对旧版本)

如果使用的是.NET Framework(非Core/.NET 5+),返回JsonResult时需要显式允许GET请求(不过你用的是POST,此步骤可选,但如果后续测试GET请求需要):

return Json("hello world", JsonRequestBehavior.AllowGet);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 10:30:16