1

我有一个应用程序是 ASP.net 核心,并集成了快速支付网关来处理支付。在我的日志文件中,我可以看到支付控制器有时会执行两次。我根据收到请求的时间生成一个 ID,这些 ID 有时相隔 1 秒,有时它们完全相同。这导致仅在发生这种情况的少数情况下对卡进行两次收费。我似乎无法弄清楚是什么触发了这种情况。

以下是我正在使用的代码

用户填写申请表并在付款按钮上单击我正在使用此代码快速触发

 $('#REG').click(function () {
            var options = {
                company_name: "abcd",
                sidebar_top_description: "Fees",
                sidebar_bottom_description: "Only Visa and Mastercard accepted",
                amount: "@string.Format("{0:c}",Convert.ToDecimal(Model.FeeOutstanding))"
            }
            document.getElementById('payment').value = 'App'
            SpreedlyExpress.init(environmentKey, options);
            SpreedlyExpress.openView();
            $('#spreedly-modal-overlay').css({ "position": "fixed", "z-index": "9999", "bottom": "0", "top": "0", "right": "0", "left": "0" });
        });

这将打开快速支付表单作为弹出窗口,用户在其中输入所有卡信息并点击支付按钮。执行支付控制器

public async Task<IActionResult> Index(DynamicViewModel model)
{
    if (ModelState.IsValid)
    {
        try
        {
            if (TempData.ContainsKey("PaymentFlag") && !String.IsNullOrEmpty(TempData["PaymentFlag"].ToString()))
            {
                // Some code logic that calls few async methods
                //generate a id based on the time of current request
                "APP-" + DateTime.Now.ToString("yyyyMMddHmmss-") + model.UserID;

                // ... Other code here     
}

我生成的 id 被记录下来,我可以在日志文件中看到它为一个客户运行了两次,该客户的 ID 要么完全相同,要么相差 1 秒。我已经测试了双击场景,并且还输入了一些代码来防止双击。但我似乎仍然无法理解为什么有时会发生这种情况。它并不频繁。就像发生在 100 次付款中的 1 例一样。

我有一个动作属性来处理重复的请求。放入此代码后,它确实停止了重复请求的数量,但并未完全停止。在少数情况下,控制器如何被调用两次。

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class NoDuplicateRequestAttribute : ActionFilterAttribute
{
    public int DelayRequest = 10;
    // The Error Message that will be displayed in case of 
    // excessive Requests
    public string ErrorMessage = "Excessive Request Attempts Detected.";

    // This will store the URL to Redirect errors to
    public string RedirectURL;

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        // Store our HttpContext (for easier reference and code brevity)
        var request = filterContext.HttpContext.Request;
        // Store our HttpContext.Cache (for easier reference and code brevity)
        var cache = filterContext.HttpContext.RequestServices.GetService<IMemoryCache>();

        // Grab the IP Address from the originating Request (example)
        var originationInfo = request.HttpContext.Connection.RemoteIpAddress.ToString() ?? request.HttpContext.Features.Get<IHttpConnectionFeature>()?.RemoteIpAddress.ToString();

        // Append the User Agent
        originationInfo += request.Headers["User-Agent"].ToString();

        // Now we just need the target URL Information
        var targetInfo = request.HttpContext.Request.GetDisplayUrl() + request.QueryString;

        // Generate a hash for your strings (appends each of the bytes of
        // the value into a single hashed string
        var hashValue = string.Join("", MD5.Create().ComputeHash(Encoding.ASCII.GetBytes(originationInfo + targetInfo)).Select(s => s.ToString("x2")));
        string cachedHash;
        // Checks if the hashed value is contained in the Cache (indicating a repeat request)
        if (cache.TryGetValue(hashValue,out cachedHash))
        {
            // Adds the Error Message to the Model and Redirect

        }
        else
        {
            // Adds an empty object to the cache using the hashValue
            // to a key (This sets the expiration that will determine
            // if the Request is valid or not)
            var opts = new MemoryCacheEntryOptions()
            {
                SlidingExpiration = TimeSpan.FromSeconds(DelayRequest)
            };
            cache.Set(hashValue,cachedHash,opts);
        }
        base.OnActionExecuting(filterContext);
    }
4

1 回答 1

0

这不是 ASP.NET Core 问题。我 99% 确定实际上有多个请求来自客户端,而 ASP.NET Core 只是按预期处理它们。

您可以选择在页面上放置一个 guid 或其他标识符,然后将其与请求一起发送。在您的 Controller 中,检查您的缓存或会话以查看该标识符是否已存在。如果确实如此,则抛出异常或返回 Ok() 或记录发生情况或在这种情况下您想要执行的任何操作,但不要向卡收费。

于 2017-05-17T01:01:24.360 回答