c# - Returning "429 Too Many Requests" from action attribute -


i'm writing class can use attribute on asp.net web api actions rate limit users based on ip address.

the logic of class works fine, , basic structure looks like:

public class throttleattribute : actionfilterattribute {      public override void onactionexecuting(httpactioncontext actioncontext)     {         // various logic determine if should respond 429          base.onactionexecuting(actioncontext);     } } 

and i'm using on controller actions adding [throttle] annotation above method definition.

somewhere in onactionexecuting method want return response 429 http code. looking @ other posts (this one example) seems can following:

actioncontext.response = actioncontext.request.createresponse(             httpstatuscode.conflict,              message.replace("{n}", seconds.tostring())         ); 

when try use code following error:

'system.net.http.httprequestmessage' not contain definition 'createresponse' , no extension method 'createresponse' accepting first argument of type 'system.net.http.httprequestmessage' found (are missing using directive or assembly reference?)

obviously, createresponse method doesn't exist on httprequestmessage, don't know how else return custom response tell user they've hit rate limit. tried this:

actioncontext.response.statuscode = httpstatuscode.badrequest; 

but resulted in error object reference not being set instance of object.

how return 429 many requests response class, or failing that, bad request response?

you throw httpresponseexception:

public override void onactionexecuting(actionexecutingcontext filtercontext) {     if (toomanyrequests()) {         throw new httpresponseexception((httpstatuscode)429);     }     base.onactionexecuting(filtercontext); } 

you can cast 429 httpstatuscode though value isn't part of enum (from c# language specification 5.0).


Popular posts from this blog