静默阻止 WEB API 方法执行

Silently prevent WEB API Method execution

我想在周末拒绝访问某些网络方法。动作过滤器似乎是实现这一目标的天然工具。

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 来默默地拒绝进入?

您可以在方法中设置响应。这里我使用了 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
        };
    }
}