我想在周末拒绝进入某些Web方法。动作过滤器似乎是天然的车辆。
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
};
}
}