悄悄地阻止WEB API方法的执行

时间:2017-09-25 17:41:33

标签: asp.net-web-api2 action-filter onactionexecuting

我想在周末拒绝进入某些网络方法。动作过滤器看起来就像是天生的工具。

public class RunMonThruFriAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(HttpActionContext actionContext)
    {
        var today = DateTime.Now.DayOfWeek;          
        if (today == DayOfWeek.Saturday || today == DayOfWeek.Sunday)
            throw new CustomException("Outside allowed or day time", 999);
    }
}

这有效,但我真的不想抛出Exception。我可以使用什么而不是Exception来默默地拒绝进入?

1 个答案:

答案 0 :(得分:1)

您可以在方法中设置响应。在这里,我使用了Unauthorized但您可以将其更改为适当的任何内容。

public override void OnActionExecuting(HttpActionContext actionContext)
{
    var today = DateTime.Now.DayOfWeek;          
    if (today == DayOfWeek.Saturday || today == DayOfWeek.Sunday)
    {
        actionContext.Response = new System.Net.Http.HttpResponseMessage
        {
            StatusCode = System.Net.HttpStatusCode.Unauthorized, // use whatever http status code is appropriate
            RequestMessage = actionContext.ControllerContext.Request
        };
    }
}