как регулировать количество запросов на пользователя, используя веб-формы asp.net - PullRequest
0 голосов
/ 26 октября 2019

мой HTML-код

      <asp:TextBox ID="Txtcomments" runat="server" TextMode="MultiLine"></asp:TextBox>
        <br />
        <asp:Button ID="BtnPost" runat="server" Text="Post" OnClick="BtnPost_Click" />
        <br />
        <asp:Label ID="Label1" runat="server" Text=""></asp:Label>

моя проблема, у меня есть образец веб-формы, подобный этому, если пользователь оставит комментарий, он сохранится в базе данных, но я должен был ограничить конкретного пользователя, как он должен сделатьтолько 2 комментария (запроса) в течение 5 минут, если тот же пользователь хочет сделать третий комментарий, он должен отображать сообщение

        protected void BtnPost_Click(object sender, EventArgs e)
    {

//first I thought like i should restrict the user using ip address so i had done this the problem with 
//this it restricts all the users of that host not a single user

        string ipaddress;
        ipaddress = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
        if (ipaddress == "" || ipaddress == null)
            ipaddress = Request.ServerVariables["REMOTE_ADDR"];
        string SessionID = Session.SessionID;


       //Throttler is the new class i have written seperately

        var Throttle = new Throttler();

        if (Throttle.RequestShouldBeThrottled(ipaddress))
        {
            Label1.Text = "Access Denied because of Too Many requests";

            TimeSpan span = (Convert.ToDateTime(Throttler.NextAccessDate) - Convert.ToDateTime(DateTime.Now));
            string diff= String.Format("{0} minutes, {1} seconds", span.Minutes, span.Seconds);
            Label4.Text = "Elapsed Time = "+" "+"Try Again After  "+diff;


        }


        else
        {

            SqlConnection con = new SqlConnection("Server=DELL-PC; User Id=sa;Password=123;Database=comments");
            con.Open();
            SqlCommand cmd = new SqlCommand("insert into tbl_comments(comment, ipAddress,  Date)values(@p1, @p2, @p4)", con);
            cmd.Parameters.AddWithValue("@p1", Txtcomments.Text);
            cmd.Parameters.AddWithValue("@p2", ipaddress);
            date = DateTime.Now.ToString();
            cmd.Parameters.AddWithValue("@p4", date);
            int i = cmd.ExecuteNonQuery();
            if (i > 0)
            {
                Label1.Text = "Your comment has been posted successfully";

                Label4.Text = " " ;
            }

            con.Close();

        }
    }

это мой класс Throttler

 public class Throttler
 {
    private int _requestLimit;
    private int _timeoutInSeconds;
    private string _key;
    public static string NextAccessDate;




    public bool RequestShouldBeThrottled(string key, int requestLimit = 5, int timeoutInSeconds = 180)
    {
        _requestLimit = requestLimit;
        _timeoutInSeconds = timeoutInSeconds;
        _key = key;

        ThrottleInfo throttleInfo = (ThrottleInfo)HttpRuntime.Cache[_key];

        if (throttleInfo == null)
        {
            throttleInfo = new ThrottleInfo
            {
                ExpiresAt = DateTime.Now.AddSeconds(_timeoutInSeconds),

                RequestCount = 0,

            };
            NextAccessDate=throttleInfo.ExpiresAt.ToString();
        } 

        throttleInfo.RequestCount++;

        HttpRuntime.Cache.Add(_key,
      throttleInfo,
      null,
      throttleInfo.ExpiresAt,
      Cache.NoSlidingExpiration,
      CacheItemPriority.Normal,
      null);

        return (throttleInfo.RequestCount > _requestLimit);
    }


}

thisмой класс ThrottleInfo

   public class ThrottleInfo
   {
    public DateTime ExpiresAt { get; set; }
    public int RequestCount { get; set; }

}

Я изменил свой исходный код и попытался использовать куки-файлы, чтобы я мог в некоторой степени ограничить конкретного пользователя, если он делает запрос от этого конкретного дротика (скажем, Google), который он ограничиваетно проблема в том, что мы знаем, что куки-файлы зависят от браузера, и один и тот же человек отправляет запросы из другого браузера (скажем, firefox), как я могу ограничить действия пользователя. вот исходный код, что я изменил по сравнению с выше

protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
 ipaddress = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
 if (ipaddress == "" || ipaddress == null&& 
 (Request.Cookies["Appcookie"]==null))
 {
  ipaddress = Request.ServerVariables["REMOTE_ADDR"];
  strSessionID = HttpContext.Current.Session.SessionID;
  HttpCookie httpCookie = new HttpCookie("Appcookie");
  UID = GetUniqueID();
  Response.Cookies["Appcookie"].Value = UID;
  httpCookie.Expires = DateTime.Now.AddDays(1);
  }
  }
  }
  private static Random random = new Random();
  private string GetUniqueID()
  {
  const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
   return new string(Enumerable.Repeat(chars,10)
  .Select(s => s[random.Next(s.Length)]).ToArray());
   }

это часть, которую я обновил, пожалуйста, помогите мне заранее спасибо

...