【问题标题】:Return custom HTTP code from ActionFilterAttribute从 ActionFilterAttribute 返回自定义 HTTP 代码
【发布时间】:2014-10-09 02:19:08
【问题描述】:
我使用下面的代码来限制我的 ASP.NET Web Api:
public class Throttle : ActionFilterAttribute
{
public override async Task OnActionExecutingAsync(HttpActionContext context, CancellationToken cancellationToken)
{
// ...
if (throttle)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Conflict));
}
}
}
但是,我无法返回错误代码 429,因为它不在 HttpStatusCode 枚举中。有没有办法返回自定义错误代码?
【问题讨论】:
标签:
asp.net
asp.net-web-api
asp.net-web-api2
【解决方案1】:
我在here 上找到了这个。
var response = new HttpResponseMessage
{
StatusCode = (HttpStatusCode)429,
ReasonPhrase = "Too Many Requests",
Content = new StringContent(string.Format(CultureInfo.InvariantCulture, "Rate limit reached. Reset in {0} seconds.", data.ResetSeconds))
};
response.Headers.Add("Retry-After", data.ResetSeconds.ToString(CultureInfo.InvariantCulture));
actionContext.Response = response;
希望对你有帮助
【解决方案2】:
这是我根据 StackOverflow 上的另一个回复所做的。
创建类(在为我工作的控制器文件中)
public class TooManyRequests : IHttpActionResult
{
public TooManyRequests()
{
}
public TooManyRequests(string message)
{
Message = message;
}
public string Message { get; private set; }
public HttpResponseMessage Execute()
{
HttpResponseMessage response = new HttpResponseMessage((HttpStatusCode)429);
if (!string.IsNullOrEmpty(Message))
{
response.Content = new StringContent(Message); // Put the message in the response body (text/plain content).
}
return response;
}
public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
{
return Task.FromResult(Execute());
}
}
在控制器中使用
public IHttpActionResult Get()
{
// with message
return new TooManyRequests("Limited to 5 request per day. Come back tomorrow.");
// without message
// return new TooManyRequests();
}