如何防止一段时间内的webapi端点
问题描述:
我正在使用web api/mvc 5并试图在一段时间内停止任何进一步的端点。是否有可能为基于ActionFilterAttribute的全局过滤器做到这一点?如何防止一段时间内的webapi端点
public override void OnActionExecuting(HttpActionContext filterContext)
{
bool isSystemShutdown = _systemService.isSystemShutdownScheduled();
if (isSystemShutdown == true)
{
return;
}
base.OnActionExecuting(filterContext);
}
答
您应该返回回应。根据需要将filterContext的Response
属性设置为有效响应。
这里我回来了200 OK。您可以随时更新它返回任何你想要的(自定义数据/消息等)
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);
}
现在你可以在Application_Start
事件global.asax.cs
GlobalConfiguration.Configuration.Filters.Add(new YourFilter());
全球注册这个如果要指定一个信息,到调用者代码,你可以做到这一点。
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);
}
这将返回一个JSON结构,如下面的200 OK响应代码。
{"message":"System is down now"}
如果你想发送不同的响应状态代码,你可以在filterContext.Response.StatusCode
属性值根据需要设置到的HTTPStatus代码。