我想在周末拒绝进入某些网络方法。动作过滤器看起来就像是天生的工具。
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
来默默地拒绝进入?
答案 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
};
}
}