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

如何向TinkoffPayments返回正确200 OK响应?ASP.NET对接问题

问题原因与解决方案

核心问题梳理

    1. ASP.NET Core 原生不支持直接将 HttpResponseMessage 作为控制器接口的返回值,框架会自动把该对象序列化为JSON结构返回,而非你预期的原生HTTP响应,Tinkoff平台无法识别这种格式的返回内容。
    1. 你之前尝试返回 Ok("OK") 不生效的原因是:该方法默认返回 Content-Type: application/json 类型的响应,实际返回内容是带双引号的 "OK",但Tinkoff要求的是纯文本格式、不带任何多余符号的 OK 字符串,二者不匹配导致校验失败。
    1. 你的代码存在显性语法错误,且所有异常都被空catch块吞掉,执行时大概率会中途崩溃:_dbContext.Notifications.Add(not); 中的 not 变量从未定义,你实际声明的变量是 notification,这行代码会直接抛出异常,而空catch块会把错误直接隐藏,接口最终返回500错误而非200响应。另外不需要手动关闭EF Core的数据库连接,框架会自动管理连接生命周期,手动关闭反而会引发额外异常。

修正后的代码实现

[HttpPost]
public async Task<IActionResult> New()
{
    string t1 = "";
    try
    {
        // 读取请求体
        using (StreamReader sr = new StreamReader(Request.Body))
        {
            t1 = await sr.ReadToEndAsync();
        }
    }
    catch (Exception e)
    {
        // 这里建议加日志记录异常,不要直接吞错
    }

    BotContext _dbContext = new BotContext(Environment.GetEnvironmentVariable("ConnectionString"));
    Notification notification = new Notification();
    
    try
    {
        TinkoffNotification tn = JsonConvert.DeserializeObject<TinkoffNotification>(t1);
        notification.Amount = tn.Amount;
        notification.Status = tn.Status;
        notification.OrderId = tn.OrderId;
        notification.PaymentId = tn.PaymentId;
        notification.Pan = tn.Pan;
        notification.RebillId = tn.RebillId;
        notification.CardId = tn.CardId;
    }
    catch
    {
        // 建议加日志
    }
    
    try
    {
        // 修正变量名错误
        _dbContext.Notifications.Add(notification);
        _dbContext.SaveChanges();
        // 去掉手动关闭连接的代码
    }
    catch 
    {
        // 建议加日志
    }

    // 返回纯文本格式的OK,符合Tinkoff要求
    return Content("OK", "text/plain", System.Text.Encoding.UTF8);
}

验证方法

用Postman或curl调用你的接口,确认满足以下三个条件即可:

  • 响应状态码为200
  • 响应体为纯文本OK(无引号、无多余空格、无换行)
  • 响应头Content-Type值为text/plain; charset=utf-8

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 08:45:03