从ActionFilterAttribute返回自定义HTTP代码

时间:2014-08-15 10:23:08

标签: asp.net asp.net-web-api asp.net-web-api2

我使用下面的代码来限制我的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枚举中。有没有办法返回自定义错误代码?

3 个答案:

答案 0 :(得分:7)

我在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;

希望这有帮助

答案 1 :(得分:0)

这是我根据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(); 

}

答案 2 :(得分:0)

在需要在ActionFilterAttribute中生成基于自定义状态代码的消息的情况下,可以通过以下方式编写:

        if (necessity_to_send_custom_code)
        {
            actionContext.Response = actionContext.Request.CreateResponse((HttpStatusCode)855, "This is custom error message for you");
        }

希望这会有所帮助。