Reputation: 2685
I'm using web api/mvc 5 and trying to stop any further endpoints for a period. Is it possible to do this for a global filter based on ActionFilterAttribute?
public override void OnActionExecuting(HttpActionContext filterContext)
{
bool isSystemShutdown = _systemService.isSystemShutdownScheduled();
if (isSystemShutdown == true)
{
return;
}
base.OnActionExecuting(filterContext);
}
Upvotes: 0
Views: 71
Reputation: 218842
You should return a response back. Set the Response
property of filterContext to a valid response as you want.
Here i am returning a 200 OK . You can update it to return whatever you want ( custom data/message etc)
public override void OnActionExecuting(HttpActionContext filterContext)
{
bool isSystemShutdown = _systemService.isSystemShutdownScheduled();
if (isSystemShutdown)
{
var r= new HttpResponseMessage(HttpStatusCode.OK);
filterContext.Response = r;
return;
}
base.OnActionExecuting(filterContext);
}
Now you can register this globally in the Application_Start
event of global.asax.cs
GlobalConfiguration.Configuration.Filters.Add(new YourFilter());
If you want to specify a message back to the caller code, you can do that.
public override void OnActionExecuting(HttpActionContext filterContext)
{
bool isSystemShutdown = _systemService.isSystemShutdownScheduled();
if (isSystemShutdown)
{
var s = new { message = "System is down now" };
var r= filterContext.Request.CreateResponse(s);
filterContext.Response = r;
return;
}
base.OnActionExecuting(filterContext);
}
This will return a JSON structure like below with 200 OK response code.
{"message":"System is down now"}
If you want to send a different response status code, you can set the filterContext.Response.StatusCode
property value to an HttpStatus code as needed.
Upvotes: 3