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



我有一个应用程序是 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" });
});

这将打开 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 个案例。

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

[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 或其他标识符,并将其与请求一起发送。在控制器中,检查缓存或会话以查看该标识符是否已存在。如果是这样,请抛出异常或返回 Ok() 或记录发生次数或在这种情况下要执行的任何操作,但不要向卡收费。

最新更新