简体   繁体   中英

How to limit requests number to an Action in period of time

How to limit incoming requests to an Action, for example I don't want to users repeatedly post data to Action. Is there any way to applying time limit for Actions?

You normally can't limit incoming requests - they are coming from machines outside of your control. What you can do is either reject requests (ie with 503 responses) or if you in some way control clients you can limit number of requests legitimate clients make.

To be able to reasonably reject incoming requests you need to know some information about previous requests for each particular user (ie last request time / index stored in cookie, or some information stored in session state). With such information you should be able to write action filter that will check for condition and reject the request.

Note that non-legitimate users will be easily able to bypass all restrictions that do not rely on server side storage (like session state). If you can't autorize users (ie by user name) restricting number of existing sessions may be problmatic too...

Here is an easy way i would do.

Create a Guid per user, along with the last post datetime, push it to user as in cookie. Everytime user posts something, read the cookie. check the datetime, if the users posted something before user can post again, return back a response, saying "slown down tiger!" otherwise proceed. You can define this Timespan yourself.

Easy no?

On the other hand, if you want for example only 10 user to invoke your action, you need a atomic counter. Interlocked is your friend. You can increment at the beginning of the method, then decrement at the end.

Oh. How about semaphores, conceptually fits your problems.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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