Silently prevent WEB API Method execution

323 views Asked by At

I want to deny entry to certain web methods on the weekends. An action filter seemed like the natural vehicle for that.

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);
    }
}

This works but I don't really want to throw an Exception. What can I use instead of the Exception to just silently deny entry?

1

There are 1 answers

0
Igor On BEST ANSWER

You can set the response in the method. Here I used Unauthorized but you can change this to whatever is appropriate.

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
        };
    }
}