繁体   English   中英

ASP.Net核心有时会动作控制器被调用两次

[英]ASP.Net core sometimes the action controller is called twice

我有一个应用程序是ASP.net核心,并已集成spreedly支付网关处理付款。 在我的日志文件中,我可以看到有时支付控制器执行两次。 我根据收到请求的时间生成一个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" });
        });

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

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秒差异的客户运行两次。 我已经测试了双击方案,并且还添加了一些代码来防止双击。 但我似乎无法理解为什么有时会发生这种情况。 它并不常见。 它就像1个案件,发生在100次付款中。

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

[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);
    }

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

您可以选择在页面上放置一个guid或其他标识符,并将其与请求一起发送。 在Controller中,检查缓存或会话以查看该标识符是否已存在。 如果是,请抛出异常或返回Ok()或记录事件或在该情况下您想要做的任何事情,但不要对卡充电。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM