【发布时间】:2015-04-23 08:06:16
【问题描述】:
我正在编写一个类,我可以将它用作我的 ASP.NET Web API 操作的属性,它将根据用户的 IP 地址对用户进行速率限制。
类的逻辑运行良好,其基本结构如下:
public class ThrottleAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
// Do various logic to determine if we should respond with a 429
base.OnActionExecuting(actionContext);
}
}
我通过在方法定义上方添加[Throttle] 注释在我的控制器操作中使用它。
在OnActionExecuting 方法的某个地方,我想用429 HTTP 代码返回一个响应。从查看其他 SO 帖子(例如this one)看来,我可以通过以下方式做到这一点:
actionContext.Response = actionContext.Request.CreateResponse(
HttpStatusCode.Conflict,
Message.Replace("{n}", Seconds.ToString())
);
当我尝试使用此代码时,我收到以下错误:
“System.Net.Http.HttpRequestMessage”不包含“CreateResponse”的定义,并且找不到接受“System.Net.Http.HttpRequestMessage”类型的第一个参数的扩展方法“CreateResponse”(您是否缺少using 指令还是程序集引用?)
显然,CreateResponse 方法在 HttpRequestMessage 上不存在,但我不知道如何返回自定义响应以告诉用户他们已达到速率限制。我也试过这个:
actionContext.Response.StatusCode = HttpStatusCode.BadRequest;
但这也导致了对象引用未设置为对象实例的错误。
我如何从我的班级返回 429 Too Many Requests 响应,或者如果失败,只返回 Bad Request 响应?
【问题讨论】:
标签: c# asp.net asp.net-web-api rate-limiting