gpt4 book ai didi

c# - 如何计算对 ASP.NET Web API POST 方法的调用

转载 作者:行者123 更新时间:2023-11-30 21:59:01 24 4
gpt4 key购买 nike

有什么方法可以统计Web API中post方法的调用次数吗?

例如:如果用户 3 次输入错误的用户名和密码组合,我想禁用该用户。因此,在连续第三次调用 Web API Controller 的 post 方法后,我想做一些事情(例如,我将以某种方式或其他方式禁用用户)。

如何计算对 API Controller 方法的调用?这种情况下是否有任何已经定义的属性或方法?

更新:

这是我的 Web API 方法:

[Route("login")]
public async Task<HttpResponseMessage> LoginUser(Login model)
{
using (AuthRepository repo = new AuthRepository())
{
Regex rgx = new Regex("[^a-zA-Z0-9 -]");
string deviceId = rgx.Replace(model.DeviceId, "");
var request = HttpContext.Current.Request;
var user = await repo.FindUserAsync(deviceId, model.PIN);
var tokenServiceUrl = request.Url.GetLeftPart(UriPartial.Authority) + request.ApplicationPath + "/Token";

if (user != null)
{
MatrixLogManager.Debug("User " + model.DeviceId + "successfully logged in on MatrixSTS.");
try
{
using (var client = new HttpClient())
{
var requestParams = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("grant_type", "password"),
new KeyValuePair<string, string>("username", deviceId),
new KeyValuePair<string, string>("password", model.PIN)
};

var requestParamsFormUrlEncoded = new FormUrlEncodedContent(requestParams);
var tokenServiceResponse = await client.PostAsync(tokenServiceUrl, requestParamsFormUrlEncoded);
var responseString = await tokenServiceResponse.Content.ReadAsStringAsync();
var responseCode = tokenServiceResponse.StatusCode;
var responseMsg = new HttpResponseMessage(responseCode)
{
Content = new StringContent(responseString, Encoding.UTF8, "application/json")
};

return responseMsg;
}
}
catch (Exception ex)
{
MatrixLogManager.Error("Error: ", ex);
throw ex;
}
}
else
{
//IF LOGIN FAILD I WOULD NEED TO COUNT SOMEHOW THAT ONE CALL WAS UNSUCCESSFUL, AFTER THIRD I WILL BLOCK USER, BUT ONLY IT HE MAKES SAME MISTAKE 3 TIMES IN A ROW.
//Adding simple int counter didn't worked for me.
return Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "Invalid username or password.");
}
}
}

最佳答案

你应该将这些东西保存在数据库中的一个名为 UserInvalidFailureLogins 的子表中:

该表将有一个指向 userId 的外键,并将有一个计数器值。

当用户尝试登录时,您首先检查用户有多少次失败以及如果他超过了阈值,那么在您重置尝试次数之前不要让他登录。

如果用户登录失败,您将计数器加 1。

关于c# - 如何计算对 ASP.NET Web API POST 方法的调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29668295/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com