1

我想拒绝在周末访问某些网络方法。动作过滤器似乎是自然的载体。

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

4

1 回答 1

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
        };
    }
}
于 2017-09-25T17:47:52.230 回答