asp.net WEBAPI implementation request frequency limit __.net

Source: Internet
Author: User
SampleController.cs
Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Threading.Tasks;
Using System.Web;
Using System.Web.Http;

Namespace App.controllers
{
    [throttle] public
    class Samplecontroller:apicontroller
    {
        [ HttpGet] public
        async task<ihttpactionresult> get () => await Task.fromresult (ok Guid.NewGuid (). ToString ());
    }
ThrottleAttribute.cs
Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Net;
Using System.Net.Http;
Using System.Threading;
Using System.Threading.Tasks;
Using System.Web;
Using System.Web.Http.Controllers;

Using System.Web.Http.Filters; namespace App {[AttributeUsage attributetargets.class | AttributeTargets.Method)] public class Throttleattribute:actionfilterattribute {private ReadOnly Handle
        Request _handlerequest;
        Public Throttleattribute () {this._handlerequest = new handlerequest (); public override Async Task Onactionexecutingasync (httpactioncontext actioncontext, CancellationToken Cancellati
            Ontoken) {var valid = await this._handlerequest.isvalidrequest (actioncontext.request); if (!valid) {actioncontext.response = new Httpresponsemessage ((httpstatuscode) 429) {REASONPH
            Rase = "Too Many requests!"}; }
        }
    }
}
HandleRequest.cs
Using System;
Using System.Collections.Generic;
Using System.Configuration;
Using System.Linq;
Using System.Net.Http;
Using System.ServiceModel.Channels;
Using System.Threading.Tasks;
Using System.Web;

Using System.Web.Caching;

        Namespace APP {public class HandleRequest {private string Name {get;} = ' Client1 '; private int Seconds {get;} = Int.


        Parse (ConfigurationManager.AppSettings.Get ("Waitmillisecond")); Public async task<bool> Isvalidrequest (httprequestmessage requestmessage) {var allowexecute = f
            Alse; Await Task.Factory.StartNew (() => {var key = string.
                Concat (Name, "-", Getclientip (Requestmessage));
                        if (httpruntime.cache[key] = = null) {HTTPRUNTIME.CACHE.ADD (key),
                        True,//This is the smallest amount of data we can have.
  NULL,//No dependency DateTime.Now.AddMilliseconds (Seconds),//absolute expiration                      Cache.noslidingexpiration, Cacheitempriority.low, Nu ll);
                No callback Allowexecute = true;


            }
            });
        return allowexecute; private string Getclientip (Httprequestmessage request) {//Get traditional context if (req Uest. Properties.containskey ("Ms_httpcontext")) {//httpcontextwrapper class is derived from the HttpContextBase class. The Httpcontextwrapper class is used as a wrapper for the HttpContext class.
                At run time, you typically invoke the members on the HttpContext object using an instance of the Httpcontextwrapper class. Return (httpcontextwrapper) request. properties["Ms_httpcontext"]).
            request.userhostaddress;
            //cs client obtains IP address//makes available the client IP address and port number associated with the remote endpoint that sent the message. if (request). Properties.containskey (Remoteendpointmessageproperty.name)) {Remoteendpointmessageproperty PR
                Op Prop = (Remoteendpointmessageproperty) requeSt.
                Properties[remoteendpointmessageproperty.name]; Return Prop.
            address;
        return null; }
    }
}
Run Result:

The result of a continuous request within 1 minutes:

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.