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

ASP.NET MVC/Web API支付网关:点击取消按钮同请求返回错误码

嘿,针对你开发的这款多客户端兼容的ASP.NET MVC/Web API支付网关,关于取消按钮返回错误码的需求,我给你整理了几个实用的实现方案,都是适配Ajax调用场景的:

方案1:返回自定义JSON结果(最推荐)

因为是Ajax调用,直接返回结构化的JSON数据是最方便前端处理的方式。你可以在控制器的Post Action里判断是否是取消操作,然后返回包含错误码的JSON对象:

// GET请求返回支付录入页面
public ActionResult PaymentEntry()
{
    return View();
}

// POST请求处理支付或取消逻辑
[HttpPost]
public ActionResult ProcessPayment(PaymentModel model)
{
    // 假设前端点击取消时,会给model传入IsCanceled=true的标识
    if (model.IsCanceled)
    {
        // 返回错误码,比如"CANCEL_001"代表用户主动取消支付
        return Json(new { Success = false, ErrorCode = "CANCEL_001", Message = "用户已取消支付" });
    }

    // 这里处理正常的支付流程逻辑
    // ...

    // 支付成功后返回跳转地址
    return Json(new { Success = true, RedirectUrl = "/Payment/Success" });
}

前端Ajax调用时,就可以根据返回的ErrorCode来执行对应的跳转逻辑:

$("#cancelBtn").click(function() {
    // 给表单添加取消标识
    $("#paymentForm").append('<input type="hidden" name="IsCanceled" value="true">');
    
    $.ajax({
        url: '/Payment/ProcessPayment',
        type: 'POST',
        data: $("#paymentForm").serialize(),
        success: function(response) {
            if (response.Success) {
                window.location.href = response.RedirectUrl;
            } else {
                // 根据错误码判断跳转目标
                if (response.ErrorCode === "CANCEL_001") {
                    window.location.href = "/Home/Index"; // 跳转到首页或指定页面
                }
            }
        },
        error: function(xhr) {
            console.error("请求处理失败,请稍后重试");
        }
    });
});
方案2:使用HttpStatusCode结果(适合Web API风格)

如果你的网关是基于Web API开发的,也可以返回带状态码的响应,同时在响应内容中携带错误码信息:

[HttpPost]
public IHttpActionResult ProcessPayment(PaymentModel model)
{
    if (model.IsCanceled)
    {
        // 返回400 Bad Request状态码,同时附带错误码详情
        return BadRequest(new { ErrorCode = "CANCEL_001", Message = "用户取消支付操作" });
    }

    // 处理正常支付流程
    // ...

    return Ok(new { RedirectUrl = "/Payment/Success" });
}

前端Ajax需要在error回调中捕获状态码并解析响应内容:

$.ajax({
    url: '/api/Payment/ProcessPayment',
    type: 'POST',
    data: JSON.stringify({ IsCanceled: true }), // 直接传取消标识
    contentType: "application/json",
    success: function(response) {
        window.location.href = response.RedirectUrl;
    },
    error: function(xhr) {
        if (xhr.status === 400) {
            const errorData = JSON.parse(xhr.responseText);
            if (errorData.ErrorCode === "CANCEL_001") {
                window.location.href = "/Home/Index";
            }
        }
    }
});
方案3:TempData + 重定向(不推荐Ajax场景,仅兼容非Ajax表单提交)

如果你的网关需要同时支持非Ajax的传统表单提交,可以用TempData存储错误码,再重定向到处理页面:

[HttpPost]
public ActionResult ProcessPayment(PaymentModel model)
{
    if (model.IsCanceled)
    {
        TempData["ErrorCode"] = "CANCEL_001";
        return RedirectToAction("HandleError");
    }

    return RedirectToAction("PaymentSuccess");
}

public ActionResult HandleError()
{
    var errorCode = TempData["ErrorCode"] as string;
    if (errorCode == "CANCEL_001")
    {
        return Redirect("/Home/Index");
    }
    return View("Error");
}

不过这个方案对Ajax不太友好,因为Ajax会捕获重定向响应,需要额外处理,所以优先推荐前两个方案。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 08:03:24